Vuex的模块化编程

1.之前我们使用store引入的时候不够简介,store为我们封装了方法

mapState:从state中获取数据,以数组的方式返回

mapGetters:从getters中获取方法,以数组的方式返回

mapMutations:从mutations中获取操作,以数组的方式返回

mapActions:从actions中获取动作,以数组的方式返回

2.我们可以通过这些方法来简化代码

有两种写法,当我们的名字和store中的名字一样时就可以使用数组的简化写法

2.1引入

复制代码
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'

2.2在method中

复制代码
    ...mapActions({'a':'add'}),
    // ...mapActions(['add']),
    ...mapMutations(['ADD'])

2.3在computed中

复制代码
    ...mapState(['sum']),
    ...mapGetters(['getT']), 

Vuex的模块化编码

1.在store下创建count.js,将上篇store中的方法封装到一个对象中并暴露

复制代码
export default {
    namespaced:true,
    //用于操作组件中的动作
    actions: {
        add(context, value) {
            context.commit('ADD', value)
        },
    },
    //用于操作数据
    mutations: {
        ADD(state, value) {
            state.sum += value
        },
    },
    //用于存储数据
    state: {
        sum: 1,
    },
    //公共方法
    getters: {
        getT(state) {
            return state.sum * 10
        }
    }
}

2.在store中引入count.js,初始化时进行模块化

复制代码
import Vue from 'vue'
import Vuex from 'vuex'


import countOptions  from './count'

Vue.use(Vuex)


//创建并暴露store
export default  new Vuex.Store({
   modules:{
     countOptions
   }
})

3.在组件中定义接收模块化Vuex的方法

3.1原生

复制代码
  methods:{  
    add(s){
        this.$store.dispatch('countOptions/add',s)
    },
     a(s){
        this.$store.commit('countOptions/ADD',s)
    }
  },
  computed:{  
    sum(){
        return this.$store.state.countOptions.sum
    },
    getT(){
        return this.$store.getters['countOptions/getT']
    }
    }, 

3.2调用Vuex中的方法

复制代码
  methods:{ 
    ...mapActions('countOptions',{'a':'add'}), 
    ...mapMutations('countOptions',['ADD'])
    // add(s){
    //     this.$store.dispatch('countOptions/add',s)
    // },
    //  a(s){
    //     this.$store.commit('countOptions/ADD',s)
    // }
  },
  computed:{ 
    ...mapState('countOptions',['sum']),
    ...mapGetters('countOptions',['getT']), 
//     sum(){
//         return this.$store.state.countOptions.sum
//     },
//     getT(){
//  return this.$store.getters['countOptions/getT']
//     }
    }, 

4.重新启动项目运行即可

相关推荐
gnip7 小时前
企业级配置式表单组件封装
前端·javascript·vue.js
一只叫煤球的猫8 小时前
写代码很6,面试秒变菜鸟?不卖课,面试官视角走心探讨
前端·后端·面试
excel8 小时前
Three.js 材质(Material)详解 —— 区别、原理、场景与示例
前端
掘金安东尼9 小时前
抛弃自定义模态框:原生Dialog的实力
前端·javascript·github
hj5914_前端新手13 小时前
javascript基础- 函数中 this 指向、call、apply、bind
前端·javascript
薛定谔的算法13 小时前
低代码编辑器项目设计与实现:以JSON为核心的数据驱动架构
前端·react.js·前端框架
Hilaku13 小时前
都2025年了,我们还有必要为了兼容性,去写那么多polyfill吗?
前端·javascript·css
yangcode13 小时前
iOS 苹果内购 Storekit 2
前端
LuckySusu13 小时前
【js篇】JavaScript 原型修改 vs 重写:深入理解 constructor的指向问题
前端·javascript
LuckySusu13 小时前
【js篇】如何准确获取对象自身的属性?hasOwnProperty深度解析
前端·javascript