【问题标题】:Vue-cli project data update delays when sending request with Vuex and axios使用 Vuex 和 axios 发送请求时 Vue-cli 项目数据更新延迟
【发布时间】:2022-01-05 12:43:11
【问题描述】:

我正在使用 Vue-CLI 开发一个项目,这是我的部分代码;

//vuex
const member = {
    namespaced:true,
    state:{
        data:[]
    },
    actions:{
        getAll:function(context,apiPath){
            axios.post(`http://localhost:8080/api/yoshi/backend/${apiPath}`, {
                action: "fetchall",
                page: "member",
            })
            .then(function(response){
                context.commit('displayAPI', response.data);
            });
        },
        toggle:(context,args) => {
        return axios
            .post(`http://localhost:8080/api/yoshi/backend/${args.address}`,
            {
                action:"toggle",
                ToDo:args.act,
                MemberID:args.id
            })
            .then(()=>{
                alert('success');
            })
    },
    },
    mutations:{
        displayAPI(state, data){
            state.tableData = data;
        },
    },
    getters:{
        getTableData(state){
            return state.tableData
        }
    }
}

//refresh function in member_management.vue

  methods: {
    refresh:function(){
      this.$store.dispatch('member/getAll',this.displayAPI);
      this.AllDatas = this.$store.getters['member/getTableData'];
    }
  }

//toggle function in acc_toggler.vue

    ToggleAcc: function (togg) {
      let sure = confirm(` ${todo} ${this.MemberName}'s account ?`);
      if (sure) {
        this.$store
          .dispatch("member/toggle", {
            address: this.displayAPI,
            id: this.MemberID,
            act: togg,
            Member: this.MemberName,
          })
          .then(() => {
            this.$emit("refresh");
          });
      }
    },

acc_toggler.vuemember_management.vue 的一个组件,我想做的是当触发 ToggleAcc() 时,它会发出 refresh() 和它请求更新的数据。

问题是,在整个过程之后,数据被更新了(我检查了数据库)但是 refresh() 函数返回了没有更新的数据,我可能需要刷新页面几次获取更新的数据(在 member_management.vue 中创建时每次都会运行refresh())

理论上,ToggleAcc 函数更新数据,refresh() 函数获取更新后的数据,我测试了几次以确保函数的执行顺序正确。

但是,情况永远不会改变。任何帮助表示赞赏!

【问题讨论】:

    标签: javascript ajax vue.js axios vue-cli


    【解决方案1】:

    代码忽略承诺控制流。所有应该被期待的承诺都应该被锁住。在函数内部使用时,应返回 Promise 以进行进一步的链接。

    它是:

    refresh:function(){
      return this.$store.dispatch('member/getAll',this.displayAPI)
      .then(() => {
        this.AllDatas = this.$store.getters['member/getTableData'];
      });
    }
    

    getAll:function(context,apiPath){
        return axios.post(...)
        ...
    

    【讨论】:

    • 天哪,它有效。救生员!非常感谢。我觉得我可能缺乏一些关于 Promise 的基本知识,我得努力了
    猜你喜欢
    • 1970-01-01
    • 2019-03-07
    • 2020-06-20
    • 1970-01-01
    • 2021-05-22
    • 2017-09-27
    • 2019-01-29
    • 2021-04-28
    • 1970-01-01
    相关资源
    最近更新 更多