// store 文件下的index.js
import state from "./states";
import actions from "./actions";
import mutations from "./mutations";
import city from './module/city'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state,
mutations,
actions,
modules: {
city
}
})
// city.js
const state = {
list: ['a', 'b'],
count: 0
}
const mutations = {
mutations_push(state, text) {
state.list.push(text)
},
mutations_add(state) {
state.count++
},
mutations_reduce(state) {
state.count--
}
}
const actions = {
actions_push: ({ commit }, text) => {
commit('mutations_push', text)
},
actions_add: ({ commit }) => {
commit('mutations_add')
},
actions_reduce: ({ commit }) => {
commit('mutations_reduce')
}
}
export default {
namespaced: true,
state,
actions,
mutations
}
// 测试页面 test.vue
ceshi
- {{item}}
添加列表
add
{{count}}
reduce
/* eslint-disable */
// 用法1
// import { mapState, mapActions } from "vuex";
// 用法2
import { mapState: mapStateGlobal, mapActions: mapActionGlobal, createNamespacedHelpers } from "vuex";
const { mapState: mapStateCity, mapActions: mapActionsCity } = createNamespacedHelpers("city");
export default {
data: function() {
return {};
},
computed: {
// 对应上面的用法1
// ...mapState("city", {
// list: state => state.list
// })
// 对应上面的用法2
...mapStateCity({
list: state => state.list,
count: state => state.count
}),
...mapStateGlobal({
// 实际代码自行配置
})
},
methods: {
// ...mapActions("city", ["actions_push", "actions_add", "actions_reduce"]), // 对应上面的用法1
...mapActionsCity (["actions_push", "actions_add", "actions_reduce"]), // 对应上面的用法2
...mapActionGlobal(/** 实际代码自行配置 */)
push() {
this.actions_push(Math.floor(Math.random() * 100));
// 直接调用 mutations 中的方法
// this.$store.commit("city/actions_push", Math.floor(Math.random() * 100));
},
add() {
this.actions_add();
},
reduce() {
this.actions_reduce();
}
}
};