Vue,等待观看

问题描述 投票:0回答:2

我的应用程序中有类似的架构。

computed(){ 
   someStoreValue = this.$store.someStoreValue; 
}
watch() { 
   someStoreValue() = async function () { 
    //do some async action 
   
   }
}, 
methods: { 
  someAction() {        
     this.$store.someStoreValue = 'NEW VALUE'     
     //await for "watch" 

     //do stuff

  }
}

我需要“someAction”等待“someStoreValue”观察者结束。 我需要这种架构 someStoreValue 可以在很多地方改变。

vue.js async-await vuex
2个回答
17
投票

当然,你不能让你的观察者异步,这是非常没有意义的,因为你想要的数据已经到达了。

someStoreValue(newValue, oldValue) { 
    // But you can still call other async functions. 
    // Async functions are just functions that returns a promise. Thus:
    doSomeAsyncAction().then(this.someAction)
}

不过,为什么不在 someAction 中执行异步操作呢?

watch:{ 
    someStoreValue(newValue, oldValue) { 
        this.someAction()
    }
},
methods:{
    async someAction(){
        await doSomeAsyncStuff() // What prevents you from doing this?
        //do stuff
    }
}

2
投票

您可以使用标志并等待。

data() {
   return {
      flag: false
   }
},
watch() { 
   someStoreValue() = async function () { 
    //do some async action 
  
     flag = true;  
   }
}, 
methods: { 
  async someAction() {        
     this.$store.someStoreValue = 'NEW VALUE'     
     await new Promise((resolve) => {
       if (this.flag) {
         resolve();
       } else {
         const unwatch = this.$watch('flag', (newVal) => {
           if (newVal) {
             unwatch();
             resolve();
           }
         });
       }
      });

     //do stuff

  }
}

也许在这种情况下,@ippi解决方案更好,但您可以在其他情况下使用此方法。

© www.soinside.com 2019 - 2024. All rights reserved.