Vue学习笔记-模块化+命名空间

目的

让代码更好维护,让多种数据分类更加明确(不同的模块挤在一个index.js中显得臃肿且不方便管理)

实现方式

  1. 修改store/index.js(也可以将不同模块分别写在不同的js文件中)

    javascript 复制代码
    const countAbout = {
    	//开启命名空间
        namespaced:true,
        actions:{
        	......
        },
        mutations:{
            ......
        },
        state:{
            sum:0,
        },
        getters:{
            bigSum(state){
                return state.sum*10
            }
        }
    }
    
    const personAbout = {
    	namespace = true,//开启命名空间
    	state = {
    		list:[xxx]
    	},
    	mutations = {...},
    	actions = {...}
    }
    
    const store = new Vuex.Store({
    	modules:{
    		countAbout,
    		personAbout
    	}
    })
  2. 开启命名空间后,组件读取各个模块的state数据

    javascript 复制代码
    //方式一:直接读取
    this.$store.state.countAbout.sum
    //方式二:借助mapState读取
    ...mapState('countAbout',['sum',...])
  3. 组件读取各个模块的getters数据

    javascript 复制代码
    //方式一:直接读取
    this.$store.getters['personAbout/firstPersonName']
    //方式二:借助mapGetters读取
    ...mapGetters('personAbout',['firstPersonName'])
  4. 组件调用dispatch

    javascript 复制代码
    //方式一:直接调用
    this.$store.dispatch('personAbout/addPerson',value)
    //方式二:借助mapActions
    ...mapActions('personAbout',{addPerson:'addPerson'})
  5. 组件调用commit

    javascript 复制代码
    //方法一:直接调用
    this.$store.commit('personAbout/ADD_PERSON',value)
    //方式二:借助mapMutations
    ...mapMutations('personAbout',{ADD_PERSON:'ADD_PERSON'})

注意:mapActions和mapMutation中无法填写函数参数,需要在html组件的@click方法声明中自己填写

相关推荐
一隅论数智2 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
XiHongShi20162 天前
STM32F407 RTC定时器例程,建议保存
stm32·单片机·学习
A黄俊辉A2 天前
uniapp webview中实现 app和内嵌的H5双向通信
vue.js·json
爱吃苹果的日记本2 天前
离散数学第六课
学习·离散数学
AI职业加油站2 天前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
深圳老胡2 天前
STM32F407 控制 L6470 步进电机驱动 —— 控制过程简介
笔记·stm32·单片机·嵌入式硬件·代码规范
旖旎夜光2 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
奇思妙想聪明勤奋的小羊2 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
honkun62 天前
vue 表格组件 vxe-table 配置 ajax 请求自动加载数据与表单查询
vue.js·vxe-table