二十六、Vuex异步获取数据的步骤

Vuex封装使用

import { getInfo } from "../../api/user" //axios二次封装接口的导入
import { getToken } from '@/utils/auth' //获取token

//vuex的基本数据,state用来存储变量
const state = {
  Infor: "",
  token: getToken(),
};

//异步操作数据    (action异步操作数据的地方)
const actions = {
  //getpersonal组件呐请求数据名
  async getpersonal ({ commit }) {
    let result = await getInfo(state.token);
    console.log(result)
    if (result.code == 200) {
      commit('GETPERSONAL', result.data[0])
    }
  }
};

//处理数据 mutation:提交更新数据的方法,必须是同步的(如果需要异步使用action)。
//每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。
const mutations = {
  PERSONALINfOR (state, data) {
    state.Infor = data
  }
};
//相当于计算属性
const getters = {};

export default {

  state,

  mutations,

  actions,

  getters
}

调用Vuex封装的函数

  mounted() {
    this.$store.dispatch("getpersonal");
  },

 使用Vuex的值 (Vuex模块化 其中一个模块personalData)

  computed: {
    personalIfor: function () {
      return this.$store.state.personalData.Infor; //模块化访问方式
    },

 

posted on 2022-06-02 23:52  QiKS  阅读(562)  评论(0)    收藏  举报

导航