Vue.js中对css的操作(修改)具体方式详解

2020-06-14 06:29:26易采站长站整理


data() {
return {serd:true,slid:true}
},
computed: {
compuretu: function() {
return {compuretu: this.serd && this.slid}
}
}

设置样式

.compuretu{color:white;background: red}

3.操作节点

由于vue本身是虚拟dom如果通过document来进行节点样式更改的时候有可能会出现’style’ is not definde的错误,

这个问题的解决方式就必须得对vue 的理解要求更高一层了,它可以通过在vue本身的周期mounted函数里用ref和$refs 来获取样式,来完成对其样式的更改:示例如下:


<template>
<div>
<div style=“color: green;” ref="abc"><span>我的test</span></div>
</div>
</template>
<script>
export default {
name: 'mytest',
data() {
return {}
},
mounted() {console.log(this.$refs.abc.style.cssText)}
}
<script>
<style>
</style>

说明:

1.ref被用来给元素(子组件)注册引用信息;

2.vm.$refs 一个对象,持有已注册过 ref 的所有子组件(或HTML元素);

使用:在 HTML元素 中,添加ref属性,然后在JS中通过vm.$refs.属性来获取

上述会将style的内容全部输出(color: green;)

这样的话对其进行更改就可以对相应的属性直接更改(

this.$refs.abc.style.color=red


<template>
<div>
<div :class='{mycss}'><span>我的单个class属性的test</span></div>
<div class='mycolor' :class="{'colordisplay':display}"><span>1.1我的对象更改&&绑定test</span></div>
<div :style='mypagestyle'><span>1.3我的样式内联更改&&绑定test</span></div>
<div :style="[myarr,myarrtest]"><span>1.3我的数组更改&&绑定test</span></div>
<div class='computed' :class='compuretu'>2.计算属性判断</div>
<div style="color: green;" ref="abc"><span>3.我的dom更改test</span></div>
</div>
</template>
<script>
export default {
name: 'mytest',
data() {
return {
serd:true,
slid:true,
mycss: {
color: ''
},
mypagestyle:{
color: 'yellow',
background:"blue"
},
myarr:{
color: 'white'
},
myarrtest:{
background:'#000',
display:'inline'
},
display: true
}
},
mounted() {  
console.log(this.$refs.abc.style.cssText)
this.$refs.abc.style.color = 'red' //修改属性
this.$refs.abc.style.background = 'black' //新增属性