<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title> Vue学习第二天 </title>
<script type="text/javascript" src="../js/vue.js"></script>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<style>
.hasBorder {
border-top-style: dotted;
border-right-style: solid;
border-bottom-style: dotted;
border-left-style: solid;
}
.noBorder {
border-style: "none"
}
.bgColorRed {
background-color: red
}
.bgColorGreen {
background-color: green;
}
.fontMax {
font-size: larger;
}
.fontMin {
font-size: small;
}
</style>
</head>
<body>
<div id="root">
<!-- 样式类名不确定 -->
<div :class="dynamicClass"> 这是一个测试(字符串拼接) </div>
<br>
<br>
<button @click="change">随机样式</button>
<br>
<br>
<!-- 样式类目和数量都不确定 -->
<div :class="classArray"> 这是一个测试(数组) </div>
<br>
<br>
<button @click="changeArray">随机样式</button>
<br>
<br>
<!-- 样式类名和个数都确定,但是否启用不确定 -->
<div :class="classObject"> 这是一个测试(对象) </div>
<br>
<br>
<button @click="changeObject">随机样式</button>
<hr />
<!-- 使用内联样式对象配置 -->
<div :style="styleObject"> 这是一个测试(内联样式对象) </div>
<br>
<br>
<button @click="changeStyleObject">随机样式</button>
<br>
<br>
<div :style="styleArray"> 这是一个测试(内联样式数组) </div>
</div>
<script type="text/javascript">
const vm = new Vue({
el: '#root',
data() {
return {
border: ["noBorder", "hasBorder"],
bgColor: ["bgColorGreen", "bgColorRed"],
font: ["fontMax", "fontMin"],
dynamicClass: "noBorder bgColorGreen fontMin",
classArray: ["hasBorder", "bgColorRed", "fontMin"],
classObject: {
hasBorder: false,
bgColorGreen: false,
fontMax: false
},
fontSize: 10,
// 内联样式对象
styleObject: {
fontSize: 10 + "px",
backgroundColor: "red"
},
styleObject1: {
color: "red",
backgroundColor: "red"
},
// 内联样式数组
styleArray: [
{
color: "green",
backgroundColor: "red"
}
]
}
},
// 所有的方法都要放在这里,标识被vue管理
methods: {
change() {
const index1 = Math.floor(Math.random() * 2)
const index2 = Math.floor(Math.random() * 2)
const index3 = Math.floor(Math.random() * 2)
// console.log(index1, index2, index3)
// console.log(this.border[index1] + " " + this.bgColor[index2] + " " + this.font[index3])
this.dynamicClass = this.border[index1] + " " + this.bgColor[index2] + " " + this.font[index3]
},
changeArray() {
const index1 = Math.floor(Math.random() * 2)
const index2 = Math.floor(Math.random() * 2)
const index3 = Math.floor(Math.random() * 2)
this.classArray = [this.border[index1], this.bgColor[index2], this.font[index3]]
},
changeObject() {
this.classObject.hasBorder = true
this.classObject.bgColorGreen = true
this.classObject.fontMax = true
},
changeStyleObject() {
console.log(this.styleObject.fontSize)
this.styleObject.fontSize = this.fontSize++ + "px"
}
},
computed: {
}
});
</script>
</body>
</html>
简而言之:
- 名称不确定就用字符串形式指定
- 名称和数量都不确定就用数组形式指定
- 名称和数量都确定,但是否启用不确定,用对象指定