
安装
npm install vuex -D
引入使用
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import actions from './actions'
import mutations from './mutations'
import getters from './getters'
Vue.use(Vuex); //类似vue-router,插件
let state = {
goods:[]
};
export default new Vuex.Store({
state,
actions,
mutations,
getters
})
//
export default new Vuex.Store({
modules: {
common, menu
},
strict: process.env.NODE_ENV !== 'production'
})
main.js
import store from './store'
new Vue({
store,
...
})
mutations-type 规范数据(cost 常量)
export const CHANG_NUM = 'CHANG_NUM' ;
export const DELETE_GOOD = 'DELETE_GOOD';
actions
import * as types from './mutations-type'
export default {
/* dispatch: ƒ boundDispatch(type, payload)
commit: ƒ boundCommit(type, payload, options)
getters: {}
state: {__ob__: Observer}
rootGetters: {}
rootState: {__ob__: Observer} */
参数一: store ,commit 为store解构 参数二:数据
changeNum({ commit }, payload) {
commit(types.CHANG_NUM,payload)
}
}
mutations
import * as types from './mutations-type'
export default{
[types.CHANG_NUM](state, payload){
state.good_list[0].num = 3 ;
}
}
view
- state渲染视图,使用计算属性 + 映射
import { mapState } from 'vuex'
computed:{
...mapState(['state.属性名'])
}
- 改变state,使用actions
import { mapActions } from 'vuex'
methods:{
...mapActions(['methods名'])
}
actions(可以包含任意异步操作)
- 触发mutations
export default {
initGoods( { commit }, data){
// commit 为 Store的解构 {getters: {…}, state: {…}, rootGetters: {…}, dispatch: ƒ, commit: ƒ, …}
// data 只能传入一个参数,多个参数使用对象Object
commit(['mutations 的 method 名'])
}
}
mutations(必须为同步操作)
initGoodsMutataion( state, data) {
// 参数1: state 参数2: data
state.xxx //数据
}