Javascript Vuex:仅当存储属性存在时,才每2秒分派一个函数?
我试图运行一个函数,该函数发出GET请求以更新产品的数量,但仅当Javascript Vuex:仅当存储属性存在时,才每2秒分派一个函数?,javascript,vue.js,vuejs2,vuex,Javascript,Vue.js,Vuejs2,Vuex,我试图运行一个函数,该函数发出GET请求以更新产品的数量,但仅当currentProductstore属性存在时。如果没有选择的产品,那么我不想让interval无缘无故地启动一个函数 在伪代码中,我基本上想说: 如果$this.store.getters['myStore/getCurrentProduct'] 然后是setInterval(这是.store.dispatch('updatequality'),2000) 我唯一的想法是为currentProduct生成一个计算属性: comp
currentProduct
store属性存在时。如果没有选择的产品,那么我不想让interval无缘无故地启动一个函数
在伪代码中,我基本上想说:
如果$this.store.getters['myStore/getCurrentProduct']然后是setInterval(这是.store.dispatch('updatequality'),2000) 我唯一的想法是为currentProduct生成一个计算属性:
computed: {
currentProd() {
return $this.store.getters['myStore/getCurrentProduct'];
}
}
然后看它:
watch: {
currentProd(newVal,oldVal) {
if (newVal != null) {
let foo = setInterval(this.$store.dispatch('updateQuantity'), 2000);
}
}
}
我只是不知道如何避免重叠和大量间隔触发。您应该将间隔对象存储在一个位置,以便轻松重置它,而不是每次观察者运行时在函数中创建新的本地间隔:
数据(){
返回{
productCheckInterval:空
}
},
观察:{
当前产品(新值、旧值){
clearInterval(this.productCheckInterval)
如果(newVal!==null){
this.productCheckInterval=setInterval(()=>{
此.$store.dispatch('updateQuantity'))
}, 2000)
}
}
}
setTimeout
怎么样?好吧,setInterval
最好每X秒启动一次……setTimeout将只启动一次,每次超时使用updatequality in store.js中的setInterval
。并使用if(foo)
。