第四章 v-bind以及class与style的绑定

2019-10-11  本文已影响0人  kzc爱吃梨

应用场景: DOM 元素经常会动态地绑定一些 class 类名或 style 样式

4.1 了解bind指令

—v-­bind的复习
链接的 href 属性和图片的 src 属性都被动态设置了,当数据变化时,就会重新渲染。
在数据绑定中,最常见的两个需求就是元素的样式名称 class 和内联样式 style 的动态绑定,它们也是 HTML的属性,因此可以使用v-­bind指令。我们只需要用 v­-bind计算出表达式最终的字符串就可以,不过有时候表达式的逻辑较复杂,使用字符串拼接方法较难阅读和维护,所以 Vue.js 增强了对 class 和 style 的绑定。


4.2 绑定 class 的几种方式

4.2.1 对象语法

给 v-­bind:class 设置一个对象,可以动态地切换 class,* 值对应true ,false
当 class 的表达式过长或逻辑复杂时,还可以绑定一个计算属性,这是一种很友好和常见的
用法,一般当条件多于两个时, 都可以使用 data 或 computed 效果展示

4.2.2 数组语法

当需要应用多个 class 时, 可以使用数组语法 , 给:class 绑定一个数组,应用一个 class
列表:
数组成员直接对应className--类名

  <style>
    .btnBg1 {
      background: red;
    }
    .btnBg2 {
      background: blue;
    }
    .active1 {
      background: yellow;
    }
    .active2 {
      background: green;
    }
    .bgColor {
      background: orange;
      width: 100px;
      height: 100px;
    }
    .borderColor {
      border: 10px solid grey;
    }
  </style>
  
<body>
  
  绑定class对象语法:对象的键是类名,值是布尔值 
  <div class="demo">
    <button :class={btnBg1:isRed,btnBg2:isBlue} @click='changeColor'>点击我切换颜色</button>
    
   <button :class='active' @click='activeColor'>计算属性绑定属性</button> <hr>
    绑定class数组语法:对象的键是类名,值是布尔值 <br>
    <div :class=[bgColor,borderColor]></div>
  </div>
  
  <script>
    //需求:点击一个按钮来回切换背景色
    let app = new Vue({
      el: '.demo',
      data: {
        isRed: true,
        isBlue: false,
        isActive1: true,
        isActive2: false,

        bgColor: "bgColor",
        borderColor: "borderColor"
      },
      computed: {
        active: function(){
          return {
            active1: this.isActive1,
            active2: this.isActive2
          }
        }
      },
      methods: {
        changeColor: function(){
          this.isRed = !this.isRed
          this.isBlue = !this.isBlue
        },
        activeColor: function(){
          this.isActive1 = !this.isActive1
          this.isActive2 = !this.isActive2
        }
      }
    })
  </script>

可以用三目运算实现,对象和数组混用——————看演示

  绑定class <br>
  <div id="app">
    数组和对象数的混用,第一个成员是对象,第二个成员是数组成员
    <div :class= "[{'active': isActive}, bgColor]"></div>
  </div>
  
  <script>
    let app = new Vue({
      el: '#app',
      data: {
        isActive: true,
        bgColor: 'bgClolor'
      }
    }) 
  </script>
image.png

4.3 绑定内联样式

使用 v-­bind:style (即:style ) 可以给元素绑定内联样式,方法与 :class 类似,也有对象语法和数组语法,看起来很像直接在元素上写 CSS:
注意: css 属性名称使用驼峰命名( came!Case )或短横分隔命名( kebab­case)

上一篇下一篇

猜你喜欢

热点阅读