vuex入门(二)之辅助api

vuex的辅助技能

modules

上篇讲解的vuex举的例子都是只有一个或者几个状态。但是如果我们有很多个组件,他们都要有很多个状态怎么办?挤在一个store.js未免太过臃肿。所以vuex提供了modules的辅助技能。

modules用法

假如我们有三个组件,分别是human,cat,dog。那么我们分别创建三个js文件用来存放三个组件所需要的state状态等

首先,创建与main.js同级的文件夹store用来存放各组件的store.js文件。然后里面再分别创建三个组件对应的store文件。
分别是:cat_store.js,dog_store.js与human_store.js

// cat_store.js,dog_store.js的内容与human_store.js一样
// human_store.js
import Vue from 'vue'
import vuex from 'vuex'

Vue.use(vuex)
export default {
    state:{
        ...
    },
    getters:{
        ...  
    },
    mutations:{
        ...  
    },
    actions:{
        ... 
    }
}

其次,再store文件夹中创建index.js文件引入各组件的store文件

import Vue from 'vue'
import vuex from 'vuex'

import human_store from 'human_store.js'
import cat_store from 'cat_store.js'
import dog_store from 'dog_store.js'

Vue.use(vuex)

export default new vuex.Store({
  modules: {
    modules1(自定义命名): human_store,
    modules2(自定义命名): cat_store,
    modules3(自定义命名): dog_store
  }
})

使用了modules之后,以human_store.js为例
调用state

this.&store.state.human_store.xxx

调用getters

this.&store.getters.human_store.xxx

调用mutations

this.&store.commit(‘xxx’) //不变


mapState、mapGetters、mapActions

有没有想过,如果我们很多个组件都用到state中的某个值,那我们岂不是要在每个组件中都要写上

this.&store.state.xxxx

这岂不是比我们使用data中的值更加繁琐?vuex的初衷不是这样的啊,应该是简洁明了的啊,这时mapXXXX诞生了

比如mapState
一般情况下,我们不想在同一个组件每次使用state的值时都这样

this.&store.state.xxxx

那么我们会通过computed

...
    computed:{
        xxxx(){
            return this.&store.state.xxxx
        },
        yyyy(){
            return this.&store.state.yyyy
        }
    }
...    

但是如果我们有很多个状态值,每个都这样写的话岂不是很多很复杂?这时我们可以使用mapState

import { mapState } from 'vuex'
...
    computed:{
        ...mapState({
            xxx:state=>state.modules1.xxx
            yyy:state=>state.modules1.yyy
        })
    }
...

这样就可以集中简便的管理。
mapActions有更简便的写法:

...
    methods:{
        ...mapActions([
            'xxx',
            'yyy',
            ....
        ])
    }
...

这种写法前提是,组件的methods中没有与’xxx’,’yyy’等相同的名字,并且store中的actions中也必须要有’xxx’,’yyy’等名字的方法

思考:为什么mapState举例的用法不可以这样用,而mapActions可以呢?

因为用了modules后,我们每次调用state,getters时都还要标明它是出自哪个modules的,但是actions却不用。上一篇写mutations时有提到,commit一个notShow,不管在哪个模块,只要有notShow都会被调用!

mapGetters、mapActions 的用法和 mapState 类似 , mapGetters 一般也写在 computed 中 , mapActions 一般写在 methods 中


最后,上篇,包括这篇所写的是没有考虑模块之间命名污染等因素,想详细了解可以参考开发文档的命名空间(namespace)的使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值