Vue,等待观看

use*_*831 3 vue.js vuex

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

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

  }
}
Run Code Online (Sandbox Code Playgroud)

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

ipp*_*ppi 7

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

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)
}
Run Code Online (Sandbox Code Playgroud)

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

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