[英]Vue watcher data not updating correctly
I have a watcher on a value of an object, I do an api call to get some data if the value is true, but it seems like the data in my local state is updating a tick too late.我有一个 object 值的观察者,如果该值为 true,我会调用 api 来获取一些数据,但似乎我本地 state 中的数据更新得太晚了。
If the condition is true nothing is set and I switch it back to false then the data is being set.如果条件为真,则未设置任何内容并将其切换回假,则正在设置数据。
This is my code:这是我的代码:
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 updates to true or false through a select option in my interface. Simulation.fetch 通过我界面中的 select 选项更新为真或假。
I am not sure what I am doing wrong here.我不确定我在这里做错了什么。 I've tried wrapping it with this.$nextTick(() => {})
but that doesn't weem to be doing anything我试过用this.$nextTick(() => {})
包装它,但这似乎没有做任何事情
You can use deep watcher for this so that the callback will be called whenever any of the watched object properties change regardless of their nested depth:您可以为此使用深度观察器,以便在任何观察到的 object 属性发生变化时调用回调,无论其嵌套深度如何:
watch: {
simulation: {
handler: function() {
console.log(this.simulation.fetch)
if (this.simulation.fetch) {
// axios call here
}
},
deep: true
}
}
Your watch code would have worked fine, if fetch
was defined in the data option and if simulation
was not a prop actually like:如果在 data 选项中定义了fetch
并且simulation
实际上不是一个 prop,那么您的 watch 代码会运行良好:
data() {
return {
loadedStores: [],
simulation: {
fetch: false
}
}
},
This change detection caveat is explained in details here此更改检测警告在此处详细说明
I tried to reproduce your problem and the only issue I see is when Simulation.fetch
starts with true
.我试图重现您的问题,我看到的唯一问题是Simulation.fetch
以true
开头。 watcher doesn't get called and for that you might use mounted()
hook 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.