Vue 组件没有检测到父挂载()提交的数据更改

  • 本文关键字:提交 数据 组件 Vue vue.js
  • 更新时间 :
  • 英文 :


我有一个简单的应用程序,它通过主实例上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.... })

最新更新