在应用界面中, 某个(些)元素的样式是变化的,class/style 绑定就是专门用来实现动态样式效果的技术
- class绑定:
:class=‘xxx’ // xxx可以是字符串、对象、数组。
字符串 表达式是字符串: ‘classA’ 适用于:类名不确定,要动态获取
对象 表达式是对象: {classA:isA, classB: isB} 适用于:要绑定多个样式,个数不确定,名字也不确定
数组 表达式是数组: [‘classA’, ‘classB’] 适用于:要绑定多个样式,个数确定,名字也确定,但不确定用不用 - style 绑定:
:style=“{ color: activeColor, fontSize: fontSize + ‘px’ }” ,其中 activeColor/fontSize 是 data 属性
对象 :style=“{fontSize: xxx}” 其中xxx是动态值。
数组 :style=“[a,b]” 其中a、b是样式对象。
<div id="root">
<h2>动态指定样式</h2>
<hr>
<!-- 绑定样式 —— 字符串写法 适用情况:样式类名不确定 需要追加-->
<h3 class="basic red" :class="login_class">未登录/注册</h3>
<button @click="login">登录</button>
<button @click="demo">随机改变样式</button>
<!-- 绑定样式 —— 数组写法 适用情况:样式类名不确定 追加个数也不确定-->
<h3 :class="class_arr">未登录/注册</h3>
<!-- 绑定样式 —— 对象写法 适用情况:样式类名确定 个数确定 但动态决定追加-->
<h3 :class="class_obj">未登录/注册</h3>
<!-- 绑定内联样式 —— 对象写法 -->
<!-- <h3 :style="{fontSize: 10+'px'}"> 内联样式指定 </h3> -->
<h3 :style="style_obj"> 内联样式对象指定 </h3>
<!-- 绑定内联样式 —— 数组写法 (极少用)-->
<h3 :style="[style_obj]"> 内联样式数组指定 </h3>
</div>
<script type="text/javascript">
Vue.config.productionTip = false
const vm = new Vue({
el: '#root',
data: {
login_class: '12',
class_arr: ['pink', 'green'],
class_obj: {
pink: true,
green: false
},
style_obj: {
fontSize: '10px'
}
},
methods: {
login() {
this.login_class = 'green'
},
demo() {
let arr = ['red', 'green', 'pink']
this.login_class = arr[Math.floor(Math.random() * 3)]
},
}
})
</script>