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

  • 31
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值