美文网首页
Vue学习笔记[04]-v-bind

Vue学习笔记[04]-v-bind

作者: 神楽花菜 | 来源:发表于2019-10-22 12:25 被阅读0次

当我们想要在html标签中想动态的绑定一些属性值的时候,我们可能会想到<img src=imageUrl alt="imageAlt">但是这样浏览器会将imageUrl当做一个地址来解析.因此需要用到v-bind来动态的绑定属性.

<img v-bind:src=imageUrl alt="imageAlt">
 const vm = new Vue({
    el: "#app",
    data: {
      imageUrl:"https://cn.vuejs.org/images/logo.png"
    }
  })

动态绑定的好处是如果我们的属性是多变的且可以后续更新的,我们无需在源代码处进行修改,只需接收从服务器返回的新数据即可.

v-bind可以简写为:

<img :src=imageUrl alt="imageAlt">

v-bind绑定class属性

如果需要动态的决定标签的class属性,我们可以对class属性进行绑定,常见的方式有两种,一种是对象绑定,另一种是数组绑定.

对象绑定

语法:v-bind:class="{class1:boolean, class2:boolean}"

其中class1class2分别代表两个类名,后边更的boolean则是表示该类是否被添加,若为true则表示该类被添加.

更进一步,为了更加方便的切换类,可以将值写在data中:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>v-bind</title>
  <script src="./vue.js"></script>
  <style>
    .hide {
      display: none;
    }
  </style>
</head>

<body>
  <div id="app">
    <button @click="switchHide">{{nextState}}</button>
    <div :class="{hide:isHide}">some text</div>
  </div>
</body>

<script>
  const vm = new Vue({
    el: "#app",
    data: {
      isHide: true,
      nextState: "show"
    },

    methods: {
      switchHide: function () {
        this.isHide = !this.isHide;
        this.nextState === "show" ? this.nextState = "hide" : this.nextState = "show";
      }
    }
    
  })
</script>

</html>
简单的状态切换demo

数组绑定

在某些时候,对数组的操作是比对对象的操作方便的,例如分割数组,添加/删除数组元素等,因此数组绑定的方法也有很大的灵活性.

数组绑定语法:<div :class="[class1,class2,class3]">some text</div>

上述的两种方法的字面量都可以放在计算属性或方法中使html更加简洁.要注意的是在计算属性和方法中使用data中的数据要加this

v-bind绑定style属性

我们可以利用v-bind绑定一些CSS内联样式.一般多用在组件化开发中改变不同组件的样式.绑定样式有两种写法:

对象式:

:style="{fontSize:'15px'}":style="{'font-size':mainFontSize}"

同样上面的对象可以放在conputed和methods中.

数组式:

:style=[{styleObj1},{styleObj2},{styleObj3}]

其中的{styleObj}是上文中对象式数组.

相关文章

网友评论

      本文标题:Vue学习笔记[04]-v-bind

      本文链接:https://www.haomeiwen.com/subject/vtxqvctx.html