網(wǎng)站前端開(kāi)發(fā)框架/朋友圈產(chǎn)品推廣文案
Class數(shù)據(jù)綁定
數(shù)據(jù)綁定的一個(gè)常見(jiàn)需求場(chǎng)景是操作CSS class列表,因?yàn)?code>class是attribute(屬性),我們可以和其他attribute一樣使用v-bind
將它們和動(dòng)態(tài)的字符串綁定。但是,在處理比較復(fù)雜的綁定時(shí),通過(guò)拼接生成字符串是麻煩且容易出錯(cuò)的。因此,Vue 專(zhuān)門(mén)為class 的v-bind
用法提供了特殊的功能增強(qiáng)。除了字符串外,表達(dá)式的值也可以是數(shù)組或?qū)ο蟆?/p>
綁定對(duì)象Object
<template>
<h3>class數(shù)據(jù)綁定</h3>
<hr>
<div :class="{active:isActive,'text-danger':hasError}">isActive</div>
<button @click="exchage">切換</button></template>
<script>export default {
data(){return{isActive:true,hasError:true}
},
methods:{exchage(){this.isActive=!this.isActive}
}
}</script>
<style scoped>
.active{color:red;
}
</style>
運(yùn)行結(jié)果
未切換前:
切換后:
多個(gè)對(duì)象綁定
<template>
<h3>class數(shù)據(jù)綁定</h3>
<hr>
<div :class="classObject">isActive</div>
<button @click="exchage">切換</button></template>
<script>export default {
data(){return{classObject:{active:true,'text-danger':true}}
},
methods:{exchage(){this.classObject.active = !this.classObject.active}
}
}</script>
<style scoped>
.active{color:rgb(132, 0, 255);font-size: large;
}
</style>
運(yùn)行結(jié)果:
切換前:
切換后:
數(shù)組綁定
<template><h3>class數(shù)據(jù)綁定</h3><hr><div :class="[activeClass,errorClass]">isActive</div></template><script>export default {data(){return{activeClass: 'active',errorClass:'text-danger'}},}</script><style scoped>.active{color:red;}</style>
運(yùn)行結(jié)果:
如果你想在數(shù)組中渲染某個(gè)class,你可以使用三元表達(dá)式。
<template><h3>class數(shù)據(jù)綁定</h3><hr><div :class="[isActive ? 'active' : '']">isActive</div><button @click="exchage">切換</button></template><script>export default {data(){return{isActive:true,}},methods:{exchage(){this.isActive=!this.isActive}}}</script><style scoped>.active{color:red;}</style>
運(yùn)行結(jié)果:
切換:
數(shù)組和對(duì)象
<template><h3>class數(shù)據(jù)綁定</h3><hr><div :class="[{'active':isActive},errorClass]">isActive</div><button @click="exchage">切換</button></template><script>export default {data(){return{isActive:true,errorClass:"text-danger"}},methods:{exchage(){this.isActive=!this.isActive}}}</script><style scoped>.active{color:red;}</style>
運(yùn)行結(jié)果:
溫馨提示:
數(shù)組和對(duì)象的嵌套過(guò)程中,只能數(shù)組嵌套對(duì)象,不能反其道而行。