vuex 模拟异步调用

在页面中首先定义一个调用vuex异步函数的方法  


{{asyncData}}

vuex 中

const store = new Vuex.Store({
  state: {
    asyncData: null,
  },
  mutations: {
    SET_ASYNC_DATA(state, data) {
      state.asyncData = data;
    },
  },
  actions: {
    fetchAsyncData({ commit }) {
      // 模拟异步请求
      return new Promise(function (resolve, reject) {
        setTimeout(() => {
          const data = "异步数据";
          commit("SET_ASYNC_DATA", data);
          resolve();
        }, 1000);
      }).catch((error) => {
        reject(error);
      });
    },
  },
  getters,
});

在 调用的页面中导入辅助函数 import { mapActions, mapState } from 'vuex'

计算属性中将值映射出来 computed: {...mapState(['asyncData'])}, 

然后在methods中调用 

  ...mapActions(['fetchAsyncData']),
    async fetchData() {
      await this.fetchAsyncData();
      console.log('this.asyncData', this.asyncData);
    },

 

 

你可能感兴趣的:(javascript,vue.js,前端)