建立文件store/index.js (建立仓库)
import Vue from 'vue'
import Vuex from 'vuex'
// 导入各个模块的小仓库
import goods from './models/goods'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
getter: {
},
mutations: {
},
actions: {
},
modules: {
// 模块化 如:goods (模块名)
goods
}
})
建立文件store/goods/index.js (建立子仓库)
export default {
namespaced: true,
state: {
goodsFenlei
},
getter: {
// 类似于过滤器 对数据起到有个包装的作用
},
mutations: {
setGoodsFenlei(state,params) { // 函数调用 更改store中的数据
state.goodsFenlei = params
},
},
actions: {
// 通过commit 来调用 mutations 中的方法
// 商品分类数据列表
getGoodsFenlei(context ,params) { // context 固定参数 params 传入的参数 可以省略不写
//调动mutations更新数据
getFenletByType(params)
.then(res=>{
context.commit('setGoodsFenlei', res.data)
// 调用mutations 中的setGoodsFenlei 方法来更改store中的数据
})
}
}
}
在main.js中
import store from './store'
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
// 按需导入
import {
mapActions,
mapState,
mapMutations
} from 'vuex'
...mapState({ // 用来获取仓库中数据 写在 computed 属性中
方法名: state => state.moduleA.状态,
方法名: state => state.moduleB.状态
}),
...mapGetters({ // 对仓库中数据进行修饰 写在 computed 属性中
方法名: 'moduleA/方法名',
方法名: 'moduleB/方法名'
})
...mapActions({ // 调用方法对数据进行修改 写在 methods
方法名: 'moduleA/方法名',
方法名: 'moduleB/方法名',
}),
...mapMutations({ // 异步请求 对数据进行跟新 写在 method
方法名: 'moduleA/方法名',
方法名: 'moduleB/方法名'
})
const store = new Vuex.Store({
//存放组件状态(组件数据)
state: {
age: 0,
name: 'jack'
},
//派生出新的状态(新的数据)
getters: { //可以认为是 store 的计算属性
//参数:组件数据对象
username(state) {
return state.name + ',hello'
}
},
//更新组件状态(更新组件数据)
mutations: {
incrment(state) {
//直接更新数据
state.键 += 1
}
},
//更新组件状态(更新组件数据)
actions: {
incrmentAction(context) {
//调动mutations更新数据
context.commit(名称, 参数)
}
}
})
new Vue({
store,//激活或注册
computed: {
this.$store.state.键
this.$store.getters.键
//辅助函数
...Vuex.mapState([键1,...,键n]),
...Vuex.mapGetters([键1,...,键n])
},
action: {
this.$store.commit(名称, 参数)
this.$store.dispatch(名称,参数)
//辅助函数
...Vuex.mapMutations([键1,...,键n]),
...Vuex.mapActions([键1,...,键n])
}
})