vuex module

Vuex学习(二)--模块modules及获取根部数据或方法

2018年11月29日

16:28

1.使用modules的目的:

由于使用单一的状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂,store对象就会变得非常臃肿;为了解决这个问题,Vuex允许我们将store分隔成模块(module),每个模块拥有自己的state,mutation,action,getter,甚至是嵌套子模块

2.具体写法:

(1)在store中新建一个模块文件

 

          

export default{
    namespaced:true,
    state:{
        arr:[]
    },
    getters:{
        add(state){
            return state.arr.push({a:"123"})
        }
    },
    mutations:{
        push2(state){
            console.log("45")
            state.arr.push('2')
        },
        aaa(state){
            state.arr={a:222}  
        }
    },
    actions:{
        adda({ state, commit, rootState}){
            // commit('aaa',null,{root:true})
            commit('aaa', 'aaa', { root: true })
        }
    }
}

(2)在store中的出口文件中引入模块

这里的属性名也可以简写成  moduleA  ES6写法

index.js

(3)模块中的getters参数及其可取到的值  

    ①state:获取modules中的state数据

    ②getters:获取modules中的getters数据

    ③rootState:获取根部state数据

    ④rootGetters:获取根部getters数据

modules中的getters

(4)模块中的mutations参数及其可取到的值

    ①state:获取modules中的state数据

    ②getters:获取modules中的getters数据

    ③调用方法时传入的值

(5)模块中的actions参数及其可取到的值

    ①commit:获取模块的mutations

  commit('aaa', 'aaa', { root: true })  这样才是获得根的mutations 

    ②dispatch:获取根部actions

    ③rootState:获取根部state,rootState.数据名称

    ④rootGetters:获取根部getters,rootState.数据名称

    ⑤state:获取modules中的getters

    ⑥getters:获取modules中的getters

modules中的actions

(6)modules中的子模块

名为modoleChild的子模块

3.组件中获取数据及方法的写法

(1)获取模块中state的数据  也可以这样获取根数据 state.即可

(2)获取模块中getters的数据   这样暂时不能获得根getterts  要想获得根getters 可以使用原来的方法

                                 ...mapGetters([''])

(3)获取模块中mutations或actions的方法  

<template>
  <div class="hello">
    <div>{{nameBig}}</div>
    <button @click="aa">按钮</button>
    <button @click="age">按钮</button>
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex';
const { mapState: mapState1, mapActions, mapGetters } = createNamespacedHelpers('wang');

// import { mapState, mapActions } from "vuex";
export default {
  name: 'HelloWorld',
  props: {
    msg: String,
  },
  computed: {
    ...mapState1({
      name: (state) => state.name,
    }),
    ...mapGetters(['nameBig']),
  },
  methods: {
    ...mapActions(['age']),
    aa() {
      this.age(3);
      console.log(this.name);
    },
  },
  mounted() {
    console.log(this.nameBig)
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值