我有这个简单的脚本,每隔几分钟生成一个随机数,每次rand
不等于我想改变其背景颜色之前的那个。可能?
所以随机数生成1,1,3,当它达到3我想要高亮背景。感谢
https://jsfiddle.net/keseyxgm/1/
new Vue({
el: '#app',
data: {
rand: 0
},
mounted : function(){
var me = this;
setInterval(function(){
me.rand = Math.floor(Math.random() * 4) + 1 ;
me.$forceUpdate();
},1000)
}
})
<div id="app">
<p>{{rand}}</p>
</div>
答案 0 :(得分:2)
创建一个data属性来存储更新后的值是否与当前值不同,并将background-color
绑定到该值:
new Vue({
el: '#app',
data() {
return {
rand: 0,
diff: false
}
},
mounted() {
setInterval(() => {
let rand = Math.floor(Math.random() * 4) + 1 ;
this.diff = rand !== this.rand;
this.rand = rand;
}, 1000);
}
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
<p :style="{ 'background-color': (diff) ? 'gold' : 'initial' }">{{rand}}</p>
</div>
&#13;
答案 1 :(得分:0)
一个很好的方法是使用具有类绑定的观察者。 看看这个 js 小提琴:https://jsfiddle.net/omarjebari/wjf8qbt0/18/
<div id="app">
<div class="random-element" v-bind:class="{ active: isChanged }">{{ rand }}</div>
</div>
<script>
new Vue({
el: "#app",
data: {
rand: 0,
isChanged: false,
},
mounted : function(){
setInterval(() => {
this.rand = Math.floor(Math.random() * 4) + 1;
}, 1000);
},
watch: {
rand(newVal, oldVal) {
console.log(`${newVal} vs ${oldVal}`);
if (newVal !== oldVal) {
this.isChanged = true;
setTimeout(() => {
this.isChanged = false;
}, 300);
}
}
},
})
</script>
<style>
div.random-element {
height: 30px;
color: black;
padding: 5px;
}
div.active {
background-color: red;
}
</style>