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

相关推荐
coding随想8 分钟前
深入浅出WebGL:在浏览器中解锁3D世界的魔法钥匙
javascript
_揽31 分钟前
html如何在一张图片上的某一个区域做到点击事件
前端·html
踢足球的,程序猿34 分钟前
从 Vue 2.0 进阶到 Vue 3.0 的核心技术解析指南
前端·javascript·vue.js·前端框架·html
冷凌爱36 分钟前
Fetch与Axios:区别、联系、优缺点及使用差异
前端·node.js·js
袁煦丞1 小时前
跨平台终端王者Tabby:cpolar内网穿透实验室第632个成功挑战
前端·程序员·远程工作
Sailing1 小时前
Grafana-mcp-analyzer:基于 MCP 的轻量 AI 分析监控图表的运维神器!
前端·node.js·mcp
阿山同学.1 小时前
AWS 亚马逊 S3存储桶直传 前端demo 复制即可使用
前端·javascript·aws
Jolyne_1 小时前
grid 实现完美的水平铺满、间隔一致的自适应布局
前端·css
sunly_1 小时前
Flutter:导航固定背景图,滚动时导航颜色渐变
android·javascript·flutter
西洼工作室2 小时前
【解决导航栏字体图标渲染导致文本闪烁问题】采用腾讯视频的解决方案
前端·css·css3