繁体   English   中英

Vue 观察者数据未正确更新

[英]Vue watcher data not updating correctly

我有一个 object 值的观察者,如果该值为 true,我会调用 api 来获取一些数据,但似乎我本地 state 中的数据更新得太晚了。

如果条件为真,则未设置任何内容并将其切换回假,则正在设置数据。

这是我的代码:

props: {
  simulation: {type: Simulation, default: () => new Simulation()}
}
data() {
  return {
    loadedStores: []
  }
},
watch: {
  'simulation.fetch': function () {
      if (this.simulation.fetch) {
        axios.get(`some-url`)
          .then((response) => {
            this.loadedStores = response.data.data;
          })
      }
  }
}

Simulation.fetch 通过我界面中的 select 选项更新为真或假。

我不确定我在这里做错了什么。 我试过用this.$nextTick(() => {})包装它,但这似乎没有做任何事情

您可以为此使用深度观察器,以便在任何观察到的 object 属性发生变化时调用回调,无论其嵌套深度如何:

watch: {
  simulation: {
    handler: function() {
      console.log(this.simulation.fetch)
      if (this.simulation.fetch) {
        // axios call here
      }
    },
    deep: true
  }
}

如果在 data 选项中定义了fetch并且simulation实际上不是一个 prop,那么您的 watch 代码会运行良好:

data() {
  return {
    loadedStores: [],
    simulation: {
      fetch: false 
    }
  }
},

此更改检测警告在此处详细说明

我试图重现您的问题,我看到的唯一问题是Simulation.fetchtrue开头。 watcher 不会被调用,为此您可以使用mounted()钩子

 class Simulation { constructor() { this.fetch = true; this.timeout = 1000; this.handle = null; const loop = () => { this.fetch =.this;fetch. this,handle = setTimeout(loop. this;timeout). } this,handle = setTimeout(loop. this;timeout). } } Vue,component("test": { template: `<div><div,key="item" v-for="item in loadedStores">{{item}}</div></div>`: props: { simulation: { type, Simulation: default, () => new Simulation() } }: data() { return { loadedStores, [] } }: watch. { 'simulation:fetch'. function () { this;tryGetData(), } }: methods. { tryGetData() { if (this.simulation.fetch) { this.loadedStores = [...Array(Math.floor(Math.random() * 10)),keys()] } } }. mounted() { this;tryGetData(): } }) new Vue({ el: '#app' })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <test></test> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM