uni-app 使用vuex(vuex module)

1:uni-app 集成了vuex 直接在根目录下创建store文件夹 新建store.js

import Vue from ‘vue‘
import Vuex from ‘vuex‘
import ‘模块名称’ from ‘模块路径‘;

Vue.use(Vuex);

const $store = new Vuex.Store({
  modules: {
    ‘引入的模块名称’,
  }
});
export default $store;

2:在main.js中引入挂载store

import store  from ‘./store/store.js‘

Vue.prototype.$store = store 

3:在store文件夹下新建文件 ‘模块名称’

新建:

actions.js

getters.js

index.js

mutations.js

state.js

types.js

4:在index.js中引入

import state from ‘./states‘;
import getters from ‘./getters‘;
import mutations from ‘./mutations‘;
import actions from ‘./actions‘;

export default {
  namespaced: true, //namespaced写成true,意思就是可以用这个module名作为区分了
  state,
  mutations,
  actions,
  getters
};

 

5:actions.js

import * as TYPES from ‘./types‘  //actions分发事件类型 
const actions = {
  changeNum(context){
    context.commit(TYPES.CHANGE_NUM)
  }
};
export default actions

6:getters.js

const getters = {

};
export default getters

7:mutations.js

import * as TYPES from ‘./types‘
const mutations = {
  [TYPES.CHANGE_NUM](state){
    state.number = state.number+1
  },
};

export default mutations

8:types

export const CHANGE_NUM = ‘CHANGE_NUM‘;

9:在组件中使用

computed:{
  ...mapState({
    number:({模块名称})=>模块名称.number,
  })
},

methods: {
...mapActions({
    add:‘模块名称/模块下的方法‘
  })
}

相关文章