Vue中Class与Style几种绑定用法

操作元素的 class 列表和内联样式是数据绑定的一个常见需求。因为它们都是 attribute,所以我们可以用 v-bind 处理它们;

Tab 页的切换就是我们最常见的一个效果之一,如何让选中的标题高亮,常用的方式就是动态切换 class 。

<button
v-for="(tab, index) in tabs"
v-bind:key="index"
v-bind:class="{active: currentTab === tab}"
v-on:click="currentTab = tab"
>{{tab}}</button>
</div>

...

data:{

currentTab: "tab1",
tabs: ["tab1", "tab2", "tab3"]

}

active 这个 class 是否存在取决于后面的表达式是真值或者假值,当为真值时 active 类被添加到元素上否则没有。

我们不仅可以添加一个 class,我们还可以同时添加多个 class,并且还可以与原有的 class 共存。

<button 
    class="btn"
    v-bind:class="{'btn-primary': isPrimary, active: isActive}"
></button>
...

data: {
isPrimary: true,
isActive: true
}

渲染结果为:

<button class="btn btn-primary active"></button>

我们也可以直接绑定一个数据对象

<button class="btn" v-bind:class="activePrimary"></button>
<script>
    var vm = new Vue({
      el: "#app",
      data: {
        activePrimary: {
          'btn-primary': true, 
          'active': true
        }
      }
    });
</script>

渲染结果与上面相同。

我们也可以在这里绑定一个返回对象的计算属性。这是一个常用且强大的模式:

<div v-bind:class="classObject"></div>
...
data: {
  isActive: true,
  error: null
},
computed: {
  classObject: function () {
    return {
      active: this.isActive && !this.error,
      'btn-primary': this.error && this.error.type === 'fatal'
    }
  }
}

数组语法 我们可以把一个数组传给 v-bind:class,以应用一个 class 列表:

<div v-bind:class="[activeClass, errorClass]"></div>
...
data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}

渲染为:

<div class="active text-danger"></div>

三元表达式:

<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>

不过,当有多个条件 class 时这样写有些繁琐。所以在数组语法中也可以使用对象语法:

<div v-bind:class="[{ active: isActive }, errorClass]"></div>
<ul  v-bind:class="'dropdown-menu zmenu '+(isOpen?'active':'') "></ul>

用在组件上 当在一个自定义组件上使用 class property 时,这些 class 将被添加到该组件的根元素上面。这个元素上已经存在的 class 不会被覆盖。 例如,如果你声明了这个组件:

Vue.component('list-component', { template: '<p class="foo bar">Hi</p>' })

然后在使用它的时候添加一些 class:

<list-component class="baz boo" />

HTML 将被渲染为:

<p class="foo bar baz boo">Hi</p>

对于带数据绑定 class 也同样适用:

<list-component v-bind:class="{ active: isActive }"/>

 

当 isActive 为 truthy 时,HTML 将被渲染成为:

<p class="foo bar active">Hi</p>

 

绑定内联样式

对象语法 v-bind:style 的对象语法十分直观——看着非常像 CSS,但其实是一个 JavaScript 对象。CSS property 名可以用驼峰式 (camelCase) 或短横线分隔 (kebab-case,记得用引号括起来) 来命名:

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
...
data: { activeColor: 'red', fontSize: 30 }

直接绑定到一个样式对象通常更好,这会让模板更清晰:

<div v-bind:style="styleObject"></div>
...
data: {
  styleObject: {
    color: 'red',
    fontSize: '13px'
  }
}

 

数组语法

v-bind:style 的数组语法可以将多个样式对象应用到同一个元素上:

<div v-bind:style="[baseStyles, overridingStyles]"></div>

 

自动添加前缀

当 v-bind:style 使用需要添加浏览器引擎前缀的 CSS property 时,如 transform,Vue.js 会自动侦测并添加相应的前缀。

从 2.3.0 起你可以为 style 绑定中的 property 提供一个包含多个值的数组,常用于提供多个带前缀的值,例如:

<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>

这样写只会渲染数组中最后一个被浏览器支持的值。

posted @ 2020-11-07 14:35  7c89  阅读(407)  评论(0编辑  收藏  举报