vue3分模块中vuex的使用,modules (分模块)
vue3分模块中vuex的使用,modules (分模块)
·
存在两种情况 模块有开启命名空间和未开启命名空间的区别
默认的模块(没有加命名空间的),state 区分模块,其他 getters mutations actions 都在全局。
带命名空间 namespaced: true 的模块,所有功能区分模块,更高封装度和复用。
开启命名空间,能让代码更加的独立,以后项目开发的时候都要开启命名空间
store index.js 子模块的state建议写成函数,调用不变
import { createStore } from "vuex";
// A模块
const moduleA = {
state: {
username: "moduleA",
},
getters: {
newName (state) {
return state.username + "!!!!";
},
},
mutations: {
updateName (state) {
state.username = "moduleAAAA";
},
},
};
// B模块
const moduleB = {
namespaced: true,
state: {
username: "moduleB",
age: 2
},
getters: {
newName (state) {
return state.username + "???";
},
},
mutations: {
// 更改数据函数
updateName (state) {
state.username = 'ls'
},
updateAge (state, playLoad) {
console.log("playLoad", playLoad)
state.age += playLoad
}
},
actions: {
// 请求数据函数
updateName (ctx, count) {
console.log('触发了')
// 发请求
setTimeout(() => {
ctx.commit('updateAge', count)
}, 1000)
}
},
};
export default createStore({
// 分模块
modules: {
moduleA,
moduleB,
},
});
app.vue
<template>
<div id="container">
<!-- 1、使用A模块的state数据 -->
<p>{{ $store.state.moduleA.username }}</p>
<!-- 2、使用A模块的getters数据 -->
<p>{{ $store.getters.newName }}</p>
<!-- 1、使用B模块的state数据 -->
<p>{{ $store.state.moduleB.username }}</p>
<!-- 2、使用B模块的getters数据 $store.getters['模块名/计算属性']-->
<p>{{ $store.getters["moduleB/newName"] }}</p>
<button @click="mutationsFn">mutationsFn</button>
<button @click="actionsFn">actionsFn</button>
<p>{{ $store.state.moduleB.age }}</p>
</div>
</template>
<script>
import { useStore } from "vuex";
export default {
name: "App",
setup() {
// userStore可以拿到vuex仓库实例
const store = useStore();
// 1、使用moduleA模块state的数据
console.log(store);
console.log(store.state.moduleA.username); // moduleA
// 2、使用moduleA模块getters的数据
console.log(store.getters.newName); // moduleA!!!!
// 1、使用moduleB模块getters的数据
console.log(store.getters["moduleB/newName"]); // moduleB???
const mutationsFn = () => {
// 提交B模块的更改
store.commit('moduleB/updateName')
};
const actionsFn = () => {
// 传参用法
store.dispatch("moduleB/updateName", 6)
};
return {
mutationsFn,
actionsFn,
};
},
};
</script>
<style lang='less' scoped>
</style>
更多推荐
已为社区贡献21条内容
所有评论(0)