vue不会在数据更改
时bonded类。我用默认值声明了数据" isloading",并在HTML标签中键入,并声明了更改数据的方法。
请参阅下面的代码!
样式
.is-red{
background: red;
}
.is-blue{
background: blue;
}
脚本
export default {
created() {
this.isLoading = true;
},
mounted() {
},
data() {
return {
isloading: true
};
},
methods: {
changeColor() {
this.isLoading = !this.isLoading;
console.log(this.isLoading);
}
}
}
html
<h1 v-bind:class="{'is-blue': isLoading, 'is-red': !isLoading }">hello</h1>
<button @click="changeColor">toggle</button>
我可以在控制台日志中看到" true"one_answers" false"之间的数据切换。但是,dom没有任何变化。
有什么问题?
您用名称 isloading
声明了变量。然后您在创建中声明了载荷。vue不会观察到动态变量的更改。
要更新组件内的动态变量,请使用Vue.set()
或this.$set()
。
您的脚本:
export default {
mounted() {
},
data() {
return {
isLoading: true
};
},
methods: {
changeColor() {
this.isLoading = !this.isLoading;
}
}
}
尝试使用computed
如下
脚本
export default {
data() {
return {
isloading: true
};
},
computed:{
classes(){
return this.isloading ? 'is-blue' : 'is-red';
}
},
methods: {
changeColor() {
this.isLoading = !this.isLoading;
console.log(this.isLoading);
}
}
}
html
<h1 :class="classes">hello</h1>
<button @click="changeColor">toggle</button>