class
和 style
)????????在将 v-bind
用于 class
和 style
时,字符串拼接麻烦且易错,Vue.js 做了专门的增强。表达式结果的类型除了字符串之外,还可以是对象或数组。
v-bind:class? 简写?:class
v-bind:style? 简写?:style
let vm = Vue.createApp({
data() {
return {
myClass1: 'box box2',
myClass2: ['box', 'box2'], //推荐
myClass3: { box: true, box2: true },//推荐
myStyle1: 'background: red; color: white;',
myStyle2: ['background: red', 'color: white'],//推荐
myStyle3: { background: 'red', color: 'white' },//推荐
}
},
}).mount("#app")
示例:2秒后
改变 aaaaa??变?aaaaa
改变 bbbbb??变?bbbbb
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1{ background: red;}
.box2{ color: white;}
</style>
<script src="../vue.global.js"></script>
</head>
<body>
<div id="app">
<div :class="myClass">aaaaa</div>
<div :style="myStyle">bbbbb</div>
</div>
<script>
let vm = Vue.createApp({
data(){
return {
//myClass: 'box1 box2'
//myClass: ['box1', 'box2'],
myClass: { box1: true, box2: true },
//myStyle: 'background: blue; color: yellow',
//myStyle: ['background: blue', 'color: yellow'],
myStyle: { background: 'blue', color: 'yellow' },
}
}
}).mount('#app');
setTimeout(()=>{
//vm.myClass.pop();
vm.myClass.box2 = false;
//vm.myStyle.push('width: 300px');
vm.myStyle.background = 'pink';
}, 2000)
</script>
</body>
</html>