操作元素的 class 列表和内联款式是数据绑定的一个常见需要。因为它们都是 attribute,所以咱们能够用 v-bind 解决它们:只须要通过表达式计算出字符串后果即可。不过,字符串拼接麻烦且易错。因而,在将 v-bind 用于 class 和 style 时,Vue.js 做了专门的加强。表达式后果的类型除了字符串之外,还能够是对象或数组。

对象语法

<script>export default {  data() {    return {      test57: 'hellokugou',      isActive: true    };  },};</script><template>  <!--first 搁置字符 -->  <div>    <p class="active">{{ test57 }}</p>    <!--second 搁置对象 -->    <p :class="{active:isActive}"> hello </p>    <button @click="isActive=!isActive">change_active</button>  </div></template><style>.active{  font-size: 80px;  color: blue;}</style>

对象

<script>export default {  data() {    return {      test57: 'hellokugou',      isActive: true,      error:{},      classObj:{        active: true,        helloWorld: true,      }    };  },  computed:{    chassObjCom:function (){      return{        active:this.isActive && !this.error,        helloWorld: this.error      }    }  }};</script><template>  <!--first 搁置字符 -->  <div>    <p class="active">{{ test57 }}</p>    <!--second 搁置对象 -->    <p :class="{active:isActive}"> hello </p>    <!--和一般class一起不会笼罩 -->    <p :class="{active:isActive}" class="helloWorld"> hello </p>    <p :class="classObj">{{ test57 }}</p>    <button @click="isActive=!isActive">change_active</button>    <p :class="chassObjCom">hellokugou computed</p>  </div></template><style>.active{  font-size: 80px;  color: blue;}.helloWorld{  background: aqua;}</style>