1、分模块状态使用vuex(store/index.js):
import { createStore } from 'vuex'
// 模块A
const moduleA = {
state: () => {
return {
username: 'moduleA'
}
},
mutations: {
},
actions: {
},
getters: {
}
}
// 模块B
const moduleB = {
namespaced: true,
state: () => {
return {
username: 'moduleB'
}
},
mutations: {
updateName (state) {
state.username = 'mutations B新名字'
}
},
actions: {
// 异步操作:请求数据函数
updateName (context) {
// 发请求
setTimeout(() => {
context.commit('updateName', 'actions B新名字')
}, 1000)
}
},
getters: {
newName (state) {
return state.username + 'B模块'
}
}
}
// 创建vuex仓库并导出
export default createStore({
state: {
},
mutations: {
},
actions: {
},
modules: {
// 分模块
moduleA,
moduleB
},
getters: {
}
})
2、在组件中使用分模块的vuex数据
<template>
<h3>使用子模块的数据:</h3>
<div>
moduleA的state模块的username: {{ $store.state.moduleA.username }}
</div>
<div>
moduleB的state模块的username: {{ $store.state.moduleB.username }}
</div>
<br>
<br>
<br>
<div>
<button @click="mutationsBFn">mutationsBFn改名字</button>
</div>
<br/>
<br/>
<div>
<button @click="actionsBFn">actionsBFn改名字</button>
</div>
</template>
<script>
import { useStore } from 'vuex'
export default {
name: 'App',
setup (props) {
const store = useStore()
const mutationsBFn = () => {
store.commit('moduleB/updateName', 'mutationsBFn')
}
const actionsBFn = () => {
store.dispatch('moduleB/updateName', { test: 'test' })
}
return {
mutationsBFn,
actionsBFn
}
}
}
</script>
<style lang="less">
</style>
这里总结一下modules (分模块)存在的两种情况:
- 默认的模块( 不带命名空间 ) : 在组件或者js文件中取值或者调用对应方法时,
state
区分模块,其他getters
mutations
actions
都在全局(通俗讲就是不带命名空间子模块定义的state数据,即时变量名和全局state中定义的变量名相同,也可以通过模块名取到对应的值,例如:$store.state.模块名.变量名),但是getters
,mutations,
actions中定义的方法或属性如果跟全局中定义的相同,那么取到的是全局的
。 - 带命名空间
namespaced: true
的模块:所有功能区分模块,更高封装度和复用(同名变量或者方法,可以在多个模块中使用)。
觉得有用的朋友,可以点赞评论收藏一哈。。。