【问题标题】:Check if the dispatch vuex is done检查调度vuex是否完成
【发布时间】:2018-07-28 11:58:46
【问题描述】:

您好,我有这个创建和更新区域功能。 API调用成功后。我将再次回调 vuex 商店的调度。然后返回主区域页面。 问题是它需要大约 5 秒才能获得调度结果列表。使我的列表不更新。

在返回页面之前如何知道调度是否完成?

loadZones(){
     this.$store.dispatch('getZones');
},

createOrUpdateZone(zone, region_checkbox, callback){
     this.$http.post(process.env.API_URL +'/api/.....)
      .then(res=> {
             if(res.data.success == true){
               this.loadZones();
               this.$router.push('/zone');
            } else{
               this.has_error = true;
     })
}

【问题讨论】:

    标签: vue.js vuejs2 vuex dispatch


    【解决方案1】:

    Vuex 操作总是返回Promise,只需在getZones 操作中创建请求时添加return 以将您的ajax 请求承诺与操作返回链接,然后您可以执行以下操作:

    //... in actions, example
    getZones(context) {
       return some_http_request()
    }
    
    
    //...
    loadZones(){
        return this.$store.dispatch('getZones');
    },
    
    createOrUpdateZone(zone, region_checkbox, callback){
     this.$http.post(process.env.API_URL +'/api/.....)
      .then(res=> {
             if(res.data.success == true){
               // next "then" will be invoked when this request will be done
               return this.loadZones();
             }
             else throw new Error();
      })
      .then(() => {
          this.$router.push('/zone');
      })
      .catch(() => this.has_error = true);
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用异步等待。

      当您使 loadZones 异步函数时,您可以在调度 getZones 上使用 await。但请记住,getZones 操作应该返回一个承诺。我相信它已经返回了一个承诺,所以你只需要添加异步等待。

      async loadZones(){
           await this.$store.dispatch('getZones');
      },
      
      createOrUpdateZone(zone, region_checkbox, callback){
           this.$http.post(process.env.API_URL +'/api/.....)
            .then(res=> {
                   if(res.data.success == true){
                     this.loadZones();
                     this.$router.push('/zone');
                  } else{
                     this.has_error = true;
           })
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-21
        • 1970-01-01
        • 1970-01-01
        • 2014-07-22
        • 2010-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多