vuex modules 怎么使用?
目录结构:
a.js vuex 模块
b.js vuex 模块
index.js vuex
v.vue 结果内容显示
src\store\modules\index.js
import Vue from 'vue';
import Vuex from 'vuex';
import numbers from './a'
import count from './b'
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
count,
numbers
}
})
src\store\modules\a.js
const state = {
numbers: 11
}
const mutations = {
add(state) {
state.numbers++
},
minus(state) {
state.numbers--
}
}
const actions = {
add: ({ commit }) => {
commit('add')
},
minus: ({ commit }) => {
commit("minus")
}
}
export default {
namespaced: true, // 开启命名空间
state,
mutations,
actions
}
src\store\modules\b.js
const state = {
count: 1
}
const mutations = {
add(state) {
state.count++
},
minus(state) {
state.count--
}
}
const actions = {
add: ({ commit }) => {
commit('add')
},
minus: ({ commit }) => {
commit("minus")
}
}
export default {
namespaced: true, // 开启命名空间
state,
mutations,
actions
}
src\components\v.vue
<template>
<div>
<h2>modules vuex内容</h2>
<h3>
{{$store.state.count.count}}
{{$store.state.numbers.numbers}}
</h3>
</div>
</template>
<script>
export default {};
</script>
<style lang="scss" scoped>
</style>