Vue中给元素绑定样式
1.class样式
事先转备好若干个样式
<style>
.basic {
width: 400px;
height: 100px;
border: 1px solid black;
}
.happy {
border: 4px solid red;
;
background-color: rgba(255, 255, 0, 0.644);
background: linear-gradient(30deg, yellow, pink, orange, yellow);
}
.sad {
border: 4px dashed rgb(2, 197, 2);
background-color: gray;
}
.normal {
background-color: skyblue;
}
.atguigu1 {
background-color: yellowgreen;
}
.atguigu2 {
font-size: 30px;
text-shadow: 2px 2px 10px red;
}
.atguigu3 {
border-radius: 20px;
}
</style>
如果一个元素需要多个class样式,并且有固定的样式和动态的样式,那么固定的样式直接在元素里面写 class="xx"即可,动态的样式绑定有几种写法:
(1) 字符串写法
一共有3个动态样式,每次只需要其中一个起作用,给div绑定点击事件,每次点击都随机切换data当中mood的值。
<div class="basic" :class="mood" @click="changeMood">{{name}}</div>
new Vue({
el: '#root',
data: {
name: '测试',
mood: 'normal',
},
methods: {
changeMood() {
const arr = ['happy', 'sad', 'normal'];
//随机取得0、1、2三个数的其中一个
const index = Math.floor(Math.random() * 3);
this.mood = arr[index];
}
},
})
(2)数组写法
用数组的形式把需要的样式全部使用起来,这种写法适用于不知道该用多少样式的情况,也许会用3个样式,也许会用8个,我们只需灵活地按照需求将样式加入数组或者从数组中删除。
<div class="basic" :class="arr">{{name}}</div>
new Vue({
el: '#root',
data: {
name: '测试',
mood: 'normal',
arr: ['atguigu1', 'atguigu2', 'atguigu3'],
},
})
(3)对象写法
实现一个需求,一共有2个样式,两个样式可能都起作用,也可能都不起作用,也可能只有一个起作用,像这种情况就可以考虑用对象写法。在对象中写入2个样式,同时用true和false来控制是否生效。
当需要用的样式总个数不确定,用哪些也不确定时,用这种方法就比较灵活。
<div class="basic" :class="classObj">{{name}}</div>
new Vue({
el: '#root',
data: {
name: '测试',
mood: 'normal',
classObj: {
atguigu1: true,
atguigu2: false
},
})
2.style样式
style样式就是内联样式,直接在元素身上写style='',使用Vue来动态绑定的时候用 :style='xx'来绑定
:style="{fontSize: xxx}"其中xxx是动态值。
:style="[a,b]"其中a、b是样式对象。
<!-- 绑定style样式--对象写法 -->
<div class="basic" :style="styleObj">{{name}}</div> <br/><br/>
<!-- 绑定style样式--数组写法 -->
<div class="basic" :style="styleArr">{{name}}</div>
const vm = new Vue({
el:'#root',
data:{
name:'尚硅谷',
mood:'normal',
styleObj:{
fontSize: '40px',
color:'red',
},
styleObj2:{
backgroundColor:'orange'
},
styleArr:[
{
fontSize: '40px',
color:'blue',
},
{
backgroundColor:'gray'
}
},
})
\