我有一个简单的应用程序,它通过主实例上mounted()
生命周期钩子上的setInterval
不断更改框的背景颜色:
问题出在哪里?
如果你按下按钮(点击我(...color
属性将更改,子组件将检测到该更改。
但是当颜色动态更改(通过 setInterval
(时,您可以在控制台上看到颜色正在更改,但组件不会检测到该更改(您也可以在控制台上看到(。
我想知道什么?
只是。。。为什么组件在检测其他手动突变(通过事件...等( ?
这是代表我的应用程序的片段:
Vue.component('coloredComp', {
props: ['color'],
watch: {
color() {
console.log('changed')
}
},
template: "<div id='box' :style='{backgroundColor : color}'></div>"
})
new Vue({
el: '#app',
data() {
return {
color: 'red'
}
},
mounted() {
this.$nextTick(() => {
let colors = ['yellow', 'red', 'green', 'blue']
let i = 0;
var int = setInterval(function() {
this.color = colors[i];
console.log('the new color is : ' + window.color)
i++;
i == colors.length ? i=0 : '';
}, 2000)
})
}
})
#box {
height: 100px;
width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="color = 'blue'">click me</button>
<colored-comp :color="color"></colored-comp>
</div>
在您的
setInterval(fn
this
中未定义/未绑定
var int = setInterval(function() {
this.color = colors[i]; // < -- here this is undefined
console.log('the new color is : ' + this.color)
i++;
i == colors.length ? i=0 : '';
}, 2000)
溶液:
也
- 使用
() => {}
语法(隐式绑定this
( - 或手动绑定
setInterval( (function() { ... }).bind(this) )
- 或关闭它
const that = this; setInterval( (function() { that.... })