Vue: 样式绑定

作者: 写代码的海怪 | 来源:发表于2019-01-14 02:25 被阅读12次

    学习 Vue 的时候觉得样式绑定很简单,但是使用的时候总是容易搞晕自己。因为 :class:style 里的数组语法和对象语法和 data 里绑定的值是不太一样的。这篇文章就简单对 Vue 绑定做个总结。

    绑定Class

    对象语法

    data 里的属性是负责 toggle 是否要这个 class,也就是一般定义 Boolean 类型的值。

    <div :class="{ active: isActive, 'text-danger': hasError }"></div>
    

    这里用 isActivehasError 定义是否需要 activetext-danger 类。

    data: {
      isActive: true,
      hasError: false
    }
    

    渲染为

    <div class="active"></div>
    

    数组语法

    data 里负责定义 CSS 类名。

    <div :class="[activeClass, errorClass]"></div>
    

    这里定义了 activeClasserrorClass 的 CSS 类名是 activetext-danger

    data: {
      activeClass: 'active',
      errorClass: 'text-danger'
    }
    

    渲染为

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

    混合写法

    可以用混合的形式来绑定 class,即数组语法里写对象语法。所以 data 里的数据主要用于:

    1. 是否需要某个 class
    2. 定义 "class" 里面的类名
    <div :class="[{ active: isActive }, errorClass]"></div>
    

    这里定义了 errorClass 的 CSS 类名为 text-danger,并用 isActive 定义是否需要 active 类。

    data: {
      errorClass: 'text-danger',
      isActive: true
    }
    

    渲染为

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

    绑定Style

    对象语法

    data 里的属性是定义 style 里的值。与 class 不一样,class 是定义是否要这个 class的。

    <div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
    

    这里定义了 style 里的 colorfont-size 的值。

    data: {
      activeColor: 'red',
      fontSize: 30
    }
    

    渲染为

    <div style="color: red; font-size: 30px"></div>
    

    数组语法

    可以绑定多个样式对象到 style 上

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

    这里在 data 里用 styleObject 定义了 colorfont-size,再用 overridingStyles 定义了 backgroundmargin。然后在组件里用数组进行混合绑定。

    data: {
      styleObject: {
        color: 'red',
        fontSize: '13px'
      },
      overridingStyles: {
        background: 'green',
        margin: '13px'
      }
    }
    

    渲染为

    <div style="color: red; font-size: 13px; background: green; margin: 13px;"></div>
    

    相关文章

      网友评论

        本文标题:Vue: 样式绑定

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