> 文章列表 > Vue.js中class与style的增强绑定

Vue.js中class与style的增强绑定

Vue.js中class与style的增强绑定

目录

一、v-bind绑定class属性

(1)绑定class样式,字符串写法

(2)绑定class样式,数组写法

(3)绑定class样式,对象写法

二、v-bind绑定内联样式style

(1)绑定style样式---对象形式

(2)绑定style样式---数组写法


        在web前端应用中,操作元素的class列表的内联样式style是数据绑定style是数据绑定的一个常见需求,因为它们都是attribute,所有可以用v-bind处理它们,但若样式复杂,则需要书写长串的样式代码,这样一来,字符串拼接就比较麻烦。因此,在将v-bind用于class和style时,Vue.js做了专门的增强,表达式结果的类型除了字符串之外,还可以是对象或数组。

一、v-bind绑定class属性

若想使用类样式(即以类名定义元素的样式,类样式一般以"."号开头命令),可以通过v-bind指令绑定class属性实现:

(1)绑定class样式,字符串写法

适用于:样式的类名不确定,需要动态指定

    <div id="root"><!-- 绑定class样式,字符串写法,适用于:样式的类名不确定,需要动态指定 --><div class="basic" v-bind:class="moon" @click="doChange">{{name}}</div></div><script>const vm = new Vue({el: '#root',data: {name: "class和style增强绑定",moon: "normal"},methods: {doChange() {var arr = ["happy", "sad", "normal"];indexof = Math.floor(Math.random() * 3);this.moon = arr[indexof];}}});</script>

css样式:

        .happy {border: 4px solid red;background-color: rgba(255, 255, 0, 0.644);background: linear-gradient(30deg, yellow, pink, orange);}.sad {border: 4px dashed rgb(2, 197, 2);background-color: gray;}.normal {background-color: skyblue;}

执行结果:

(2)绑定class样式,数组写法

适用于:要绑定的样式个数不确定,名字也不确定

    <div id="root"><!-- 绑定class样式,数组写法,适用于:要绑定的样式个数不确定,名字也不确定 --><div class="basic" v-bind:class="classarr">{{name}}</div></div><script>const vm = new Vue({el: '#root',data: {name: "class和style增强绑定",classarr: ["text_1", "text_2", "text_3"],},methods: {}});</script>

css样式:

        .text_1 {background-color: yellowgreen;}.text_2 {font-size: 30px;text-shadow: 2px 2px 10px red;}.text_3 {border-radius: 20px;}

执行结果:

(3)绑定class样式,对象写法

适用于:要绑定的样式个数和名字也确定,需要动态显示 

    <div id="root"><!-- 绑定class样式,对象写法,适用于:要绑定的样式个数和名字也确定,需要动态显示 --><div class="basic" v-bind:class="classobj">{{name}}</div></div><script>const vm = new Vue({el: '#root',data: {name: "class和style增强绑定",classobj: {text_1: false,text_2: true,text_3: false,},},methods: {}});</script>

css样式:

        .text_1 {background-color: yellowgreen;}.text_2 {font-size: 30px;text-shadow: 2px 2px 10px red;}.text_3 {border-radius: 20px;}

执行结果:

二、v-bind绑定内联样式style

通过内联(style)绑定给DOM元素示例:

(1)绑定style样式---对象形式

    <div id="root">绑定style样式----对象形式<br><br><div v-bind:style="styleobj" class="basic">{{name}}</div><br><br></div><script>const vm = new Vue({el: '#root',data: {name: "class和style增强绑定",styleobj: {width: "300px",height: "100px",border: "1px solid black",fontSize: "40px",backgroundColor: "blue"},},methods: {}});</script>

执行结果:

 (2)绑定style样式---数组写法

    <div id="root">绑定style样式----数组写法<br><br><div v-bind:style="stylearr" class="basic">{{name}}</div></div><script>const vm = new Vue({el: '#root',data: {name: "class和style增强绑定",stylearr: [{width: "300px"},{height: "100px"}, {border: "1px solid black"},{backgroundColor:"red"},{fontSize:"20px"}],},methods: {}});</script>

执行结果:

早知网