08_样式绑定
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.basic {
width: 400px;
height: 100px;
margin: 0 auto;
background-color: #dcdcdc;
text-align: center;
line-height: 100px;
cursor: pointer;
user-select: none;
margin-bottom: 5px;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.radius {
border-radius: 20px;
}
.blue {
background-color: #0095ff;
}
.narrow {
width: 300px;
transition: all 0.8s;
}
</style>
<script src="./lib/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 1. 绑定class属性--字符串写法,适用于样式的类名不确定,需要动态绑定的时候 -->
<div class="basic" :class="bgc" @click="change">点我变色</div>
<!-- 2. 绑定class属性--数组写法,适用于样式的个数和类名都不确定,需要动态绑定的时候 -->
<div class="basic" :class="bgcArr">
<button @click="addGreen">绿色</button>
<button @click="addRadius">圆角</button>
</div>
<!-- 3. 绑定class属性--对象写法,适用于样式的个数和类名都确定,需要动态绑定的时候 -->
<div class="basic" :class="bgcObj">
<button @click="addBlue">蓝色</button>
<button @click="narrow">变窄</button>
</div>
<!-- 4. 绑定style属性--对象写法1(短横线分隔单词,用引号包裹)-->
<div class="basic" :style="{'background-color': active}">
<button @click="addPurple">紫色</button>
</div>
<!-- 5. 绑定style属性--对象写法2 (驼峰,这里演示对象放在data中) -->
<div class="basic" :style="styleObj">
<button @click="addPink">粉色</button>
</div>
<!-- 6. 绑定style属性--数组写法 -->
<div class="basic" :style="[styleBg, styleWidth]">
<button @click="addBrown">棕色</button>
<button @click="addWidth">变宽</button>
</div>
</div>
<script>
const vm = new Vue({
el: '#app',
data() {
return {
bgc: '',
bgcArr: [],
bgcObj: {
blue: false,
narrow: false,
},
active: '',
styleObj: {
// 这里不能自定义,必须是DOM结点元素的style属性
backgroundColor: '',
},
styleBg: {
backgroundColor: '',
},
styleWidth: {
width: '',
},
};
},
methods: {
change() {
this.bgc = 'red';
},
addGreen() {
if (this.bgcArr.indexOf('green') == -1) {
this.bgcArr.push('green');
}
},
addRadius() {
if (this.bgcArr.indexOf('radius') == -1) {
this.bgcArr.push('radius');
}
},
addBlue() {
this.bgcObj.blue = true;
},
narrow() {
this.bgcObj.narrow = true;
},
addPurple() {
this.active = 'purple';
},
addPink() {
this.styleObj.backgroundColor = 'pink';
},
addBrown() {
this.styleBg.backgroundColor = '#382626';
},
addWidth() {
this.styleWidth.width = '500px';
},
},
});
</script>
</body>
</html>
阅读剩余
THE END