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.重新启动项目运行即可

相关推荐
小小小小宇5 小时前
虚拟列表兼容老DOM操作
前端
悦悦子a啊5 小时前
Python之--基本知识
开发语言·前端·python
安全系统学习6 小时前
系统安全之大模型案例分析
前端·安全·web安全·网络安全·xss
涛哥码咖6 小时前
chrome安装AXURE插件后无效
前端·chrome·axure
OEC小胖胖6 小时前
告别 undefined is not a function:TypeScript 前端开发优势与实践指南
前端·javascript·typescript·web
行云&流水6 小时前
Vue3 Lifecycle Hooks
前端·javascript·vue.js
Sally璐璐7 小时前
零基础学HTML和CSS:网页设计入门
前端·css
老虎06277 小时前
JavaWeb(苍穹外卖)--学习笔记04(前端:HTML,CSS,JavaScript)
前端·javascript·css·笔记·学习·html
三水气象台7 小时前
用户中心Vue3网页开发(1.0版)
javascript·css·vue.js·typescript·前端框架·html·anti-design-vue
灿灿121387 小时前
CSS 文字浮雕效果:巧用 text-shadow 实现 3D 立体文字
前端·css