我们都知道Vue.js有一个特性是数据驱动视图,这样我们就不用再去修改dom,那么如何在不通过dom的情况下去动态改变我们的样式,官网给了我们几种方式,在这里我写了几个例子实现了一下(使用vue-cli):
1、在data()中绑定动态style
首先在data()中定义一个样式组TheStyle:
data(){
return{
TheStyle:{
backgroundColor:'yellow',
width:'300px',
height:'60px',
transition:'all 0.7s'
}
}
},
这里要注意css属性的命名要使用小驼峰命名法,而且属性取值要用字符串而且取值不用加';'分号,否则无法显示,
然后我们再定义一个用于测试的div:
<div :style="TheStyle" @click="changeColor"></div>
然后在div中绑定我们前面定义的TheStyle,使用:style的方式绑定data()中的TheStyle。
然后我们定义一个点击事件"changeColor"用来测试动态样式:
changeColor(){
this.$data.TheStyle.backgroundColor='black';
this.$data.TheStyle.width='50px';
},
这样就可以实现点击我们测试的div即可以变换颜色和div的大小。
2、使用refs修改style
先定义一个div用于测试:
<div style="width: 600px;height: 60px;background-color: greenyellow" ref="TheStyle2" @click="changeColor2"></div>
其中要定义一个属性ref="TheStyle2",然后定义一个测试的方法changeColor2:
changeColor2(){
this.$refs.TheStyle2.style.backgroundColor='red';
this.$refs.TheStyle2.style.width='400px';
this.$refs.TheStyle2.style.transition='all 0.9s';
},
这里可以使用this.$refs.TheStyle2.style直接修改div的style属性从而达到目的
3、动态绑定class
可以详见官方教程,说的很详细了:https://cn.vuejs.org/v2/guide/class-and-style.html
4、全部代码:
在这里是写成一个vue-cli的一个组件:
<template>
<!--Vue.js实现动态切换样式的方法-->
<div id="test">
<!--使用data动态style-->
<div :style="TheStyle" @click="changeColor"></div>
<!--使用refs调用dom-->
<div style="width: 600px;height: 60px;background-color: greenyellow" ref="TheStyle2" @click="changeColor2"></div>
<!--使用class与data的绑定-->
<div :class="{test:isActive,'atest':!isActive}" @click="isActive=!isActive"></div>
<div :class="ObjectChange" @click="ObjectChange.atest=!ObjectChange.atest;ObjectChange.test=!ObjectChange.test"></div>
<div :class="[ObjectChange,isActive]"></div>
</div>
</template>
<script>
export default {
name: "test",
data(){
return{
ObjectChange:{
test:true,
atest:false
},
isActive:true,
position:'1',
TheStyle:{
backgroundColor:'yellow',
width:'300px',
height:'60px',
transition:'all 0.7s'
}
}
},
methods:{
changeColor(){
this.$data.TheStyle.backgroundColor='black';
this.$data.TheStyle.width='50px';
},
changeColor2(){
this.$refs.TheStyle2.style.backgroundColor='red';
this.$refs.TheStyle2.style.width='400px';
this.$refs.TheStyle2.style.transition='all 0.9s';
},
}
}
</script>
<style scoped>
.atest{
width: 60px;
height: 60px;
background-color: yellow;
}
.test{
width: 60px;
height: 60px;
background-color: indianred;
}
.radial-test{
}
</style>