vuex 高级用法

992 阅读8分钟

An image

# 目录结构

  store
  -- modules
     --order.js
  -- actions.js
  -- mutations.js
  -- mutations-types.js
  -- state.js
  -- getters.js
  -- index.js

# getters

类似于 Vue 中的 计算属性,认为是 store 的计算属性

export default {
  user: state => state.user
}

# state

state来存储应用中需要共享的状态

export default {
  user: []
}

#actions

异步地更改状态,action并不直接改变state,而是发起mutation

import types from './mutations-type'
export default {
  // 方法一
  getUser: ({ commit }, data) => {
    commit(types.GET_USER, data);
  };
  // 方法二
  async fnA ({ commit }, {params1, params2}) {
    commit('getData', await getData())
  },
  async fnB ({ dispatch, commit }) {
    await dispatch('fnA') // 等待 fnA 完成
    commit('getOtherData', await getOtherData())
  }

#mutations

mutations才是改变状态的执行者。mutations用于同步地更改状态

import types from './mutations-type'
export default {
  [types.GET_USER](state, data) {
    state.user = data;
  }
}

#mutations-type.js

函数变量

export default {
  GET_USER: 'GET_USER'
}

#index.js

import Vue from 'vue';
import Vuex from 'vuex';
import actions from './actions';
import getters from './getters';
import state from './state';
import mutations from './mutations';

import order from './modules/order';

Vue.use(Vuex);

const debug = process.env.NODE_ENV !== 'production';

const store = new Vuex.Store({
  state,
  actions,
  getters,
  mutations,
  modules: {
    order
  },
  strict: debug,
});

export default store;

#order.js

const types = {

}

const dafaultState = {};

const getters = {};

const actions = {};

const mutations = {};

export default {
  namespaced: true,
  state: dafaultState,
  getters,
  actions,
  mutations
};

#组件中使用

import types from './mutations-type'
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
  computed: {
    ...mapState('order',['模块中state对象']),
    ...mapGetters('order',['模块中state对象']),
    ...mapState(['user']),
    ...mapGetters(['user']),
    order() { // 模块
      return this.$store.state.order.oderInfo
    },
    user() { // 公共
      return this.$store.state.user
    }
  },
  methods: {
    ...mapActions('order',['模块中actions方法']),
    ...mapActions(['getUser']),
    getUser() {
      this.getUser(data)
    },
    order() {
       this.$store.dispatch("order/getOrder", data) // 调用方法
    },
    user() {
      this.$store.dispatch("user") // 调用方法

      this.$store.dispatch("user").then(() => {

      })

      this.$store.commit('mutations 中的方法',data)

      this.$store.commit(types.GET_USER,data)
    },
  }
}