vue - vuex模块化
定义moon.js:
必须要在每个模块中添加namespace: true属性,不然会报错
也可以把dog模块域cat模块单独的定义在一个文件中,export defautl暴露然后moon.js引入
import Vue from 'vue' //引入vuex import Vuex from 'vuex' //使用vuex插件 Vue.use(Vuex) //模块化 //关于dog的模块 const dog={ //异步操作 actions: { }, //state成员操作 mutations: { }, //加工state成员给外界 getters: { }, //state 存放状态 state: { } } //关于cat的模块 const cat={ //异步操作 actions: { }, //state成员操作 mutations: { }, //加工state成员给外界 getters: { }, //state 存放状态 state: { } } export default new Vuex.Store({
//使用模块化 modules: { //myDog: dog, //myCat: cat dog, cat } })
模块化之后如何调用方法与数据:
map调用
<script> //引入mapActions import {mapActions,mapMutations,mapGetters,mapState} from 'vuex' export default { //mapGetters与mapState映射 computed: { //sate数组写法 ...mapState('dog',['name','age']), ...mapState('cat',['name','age']), //getters数组写法 ...mapGetters('dog',['lastName']), ...mapGetters('cat',['lastName']), //sate对象写法 ...mapState('dog',{name: 'name',age: 'age'}), ...mapState('cat',{name: 'name',age: 'age'}), //getters对象写法 ...mapGetters('dog',{lastName: 'lastName'}), ...mapGetters('cat',{lastName: 'lastName'}) }, //mapActions与mapMutations映射 methods: { //mapActions对象写法 ...mapActions('dog',{setName: 'setName'}), ...mapActions('cat',{setName: 'setName'}), //mapMutations对象写法 ...mapMutations('dog',{setName: 'SETNAME'}), ...mapMutations('cat',{setName: 'SETNAME'}), //mapActions数组写法 ...mapActions('dog',['setName']), ...mapActions('cat',['setName']), //mapMutations数组写法 ...mapActions('dog',['SETNAME']), ...mapActions('cat',['SETNAME']), } } </script>
不使用map,原生调用:
必须要在每个模块中添加namespace: true属性,不然会报错
<script> export default { methods: { mess(){ //Actions this.$store.commit(['dog/setName'],'levi') this.$store.commit(['cat/setName'],'levi') //Mutations this.$store.commit(['dog/SETNAME'],'levi') this.$store.commit(['cat/SETNAME'],'levi') //Getters this.$store.getters(['dog/lastName']) this.$store.getters(['cat/lastName']) //State this.$store.state.dog.name this.$store.state.cat.name } } } </script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类