v-bind指令解析

v-bind指令解析

v-bind绑定class

对象语法

使用v-bind:class实现动态切换class

//将active对象传给v-bind:class
<div id="app" v-bind:class="{active:'isActive'}">红色</div>

//在data中为isActive赋值,isActive为active对象的属性
var app = new Vue({
  el: '#app',
  data: {
    isActive: true
  }
})

//css代码
.active{
  color: red;
}

通过这样渲染出来的结果就是显示为红颜色的“红色”

除此之外,v-bind:class也可以绑定一个返回对象的计算属性

//将计算属性Object与v-bind:class绑定
<div id="app" v-bind:class="Object">红色</div>

//以下代码将class变为active,其属性值为true
var app = new Vue({
  el: '#app',
  data: {
    isActive: true
  },
  computed: {
    Object: function () {
      return {
        active: this.isActive
      }
    }
  },
})

//css代码
.active{
  color: red;
}

以这种方式渲染出来的结果与上一个例子相同,都是红色字体的“红色”

数组语法

也可将数组传给v-bind:class,这种方法相对少用

//将数组[activeClass,newClass]传给v-bind:class
<div id="app" v-bind:class="[activeClass,newClass]">红色</div>

//在data中将active和new两个class分别赋值给activeClass和newClass
var app = new Vue({
  el: '#app',
  data: {
    activeClass:'active',
    newClass:'new'
  }
})

//css代码,为active和new指定样式
.active{
  color: red;
}

.new{
  font-size: 35px;
}

实现出来的效果是红色35px字体”红色“

v-bind绑定style

对象语法

//将newStyle对象绑定v-bind:style
<div id="app" v-bind:style="newStyle">红色</div>

//在data中为newStyle对象的属性赋值
var app = new Vue({
  el: '#app',
  data: {
    newStyle:{
      color: 'red'
    }
  }
})

以上例子页面渲染结果为红色字体的“红色”

数组语法

//将数组[newStyle,fontStyle]与style绑定
<div id="app" v-bind:style="[newStyle,fontStyle]">红色</div>

//为newStyle和fontStyle赋值
var app = new Vue({
  el: '#app',
  data: {
    newStyle: {
      color : 'red'
    },
    fontStyle: {
      font : '35px'
    }
  }
})

这个例子渲染结果为红色35px字体的“红色”

v-bind:属性名可缩写为: 属性名,除了绑定class和style之外也可用于绑定href等属性

<div :属性="属性值"></div>
//等同于
<div v-bind:属性="属性值"></div>

猜你喜欢

转载自www.cnblogs.com/15907678645xie/p/12687788.html
今日推荐