<script>
// 注册命名空间
export const MODULEA_INCREMENT = 'modulea/increment'
export const MODULEA_ACTIONS = 'modulea/action'
export const MODULEB_INCREMENT = 'moduleb/increment'
export const MODULEB_ACTIONS = 'moduleb/action'
</script>
<script>
import Vue from 'vue'
import Vuex from 'vuex'
// 定义命名空间 避免冲突
import * as Type from './type.js'
// 告诉 vue 使用 vuex
Vue.use(Vuex)
// 定义模块A
const moduleA = {
// state 是自己的状态 不会冲突
state: {
countA: 0
},
mutations: {
[Type.MODULEA_INCREMENT] (state) {
state.countA++
}
},
actions: {
[Type.MODULEA_ACTIONS] ({state, commit}) {
commit(Type.MODULEA_INCREMENT, '小花')
}
}
}
// 定义模块B
const moduleB = {
// state 是自己的状态 不会冲突
state: {
countA: 0
},
mutations: {
[Type.MODULEB_INCREMENT] (state) {
state.countA = state.countA + 2
}
},
actions: {
[Type.MODULEB_ACTIONS] ({state, commit}) {
commit(Type.MODULEB_INCREMENT, '小花')
}
}
}
// 创建store
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
export {store}
</script>
<!-- teacher.vue -->
<template>
<div>
<Search></Search>
</div>
</template>
<script>
import {store} from './store.js'
import Search from './search.vue'
export default {
// store 提供给 store 选项 可以把store的实例注入到所有的子组件
store,
components: {
Search
}
}
</script>
<!-- search.vue -->
<template>
<div class="search">
<p>{{nameA}}</p>
<p>{{nameB}}</p>
<button @click="increment">+</button>
</div>
</template>
<script>
import * as Types from './type.js'
export default {
computed: {
nameA () {
// this.$store.state.count 获取store中的状态
return this.$store.state.a.countA
},
nameB () {
return this.$store.state.b.countA
}
},
methods: {
increment () {
// this.$store.dispatch 分发Action
// 可以添加额外参数
this.$store.dispatch(Types.MODULEA_ACTIONS)
this.$store.dispatch(Types.MODULEB_ACTIONS)
}
}
}
</script>