VueX的模块你知道多少?

在这里插入图片描述

为什么会出现VueX的模块呢?当你的项目中代码变多的时候,很难区分维护。那么这时候Vuex的模块功能就这么体现出来了。

那么我们就开始吧!
一、模块是啥?

/* eslint-disable no-unused-vars */
import Vue from ‘vue’
import Vuex from ‘vuex’

Vue.use(Vuex)

export default new Vuex.Store({
state:{
global:‘this is global’
},
// 在以下属性可以添加多个模块。如:moduleOne模块、moduleTwo模块。
modules: {
moduleOne:{},
moduleTwo:{}
}
})

二、在模块内添加state

可以直接在模块中直接书写state对象。

/* eslint-disable no-unused-vars */
import Vue from ‘vue’
import Vuex from ‘vuex’

Vue.use(Vuex)

export default new Vuex.Store({
state:{
global:‘this is global’
},
modules: {
moduleOne:{
state:{
moduleOnevalue:‘1’
}

},
moduleTwo:{
  state:{
    moduleTwovalue:'0'
  }
}

}
})

我们在页面中引用它。我们直接可以找到对应的模块返回值,也可以使用mapState方法调用。


<template>
    <div class="home">
        <p>moduleOne_state:{{moduleOne}}</p>
        <p>moduleTwo_state:{{moduleTwo}}</p>
        <p>moduleOne_mapState:{{moduleOnevalue}}</p>
        <p>moduleTwo_mapState:{{moduleTwovalue}}</p>
    </div>
</template>
<script>
import {mapState} from 'vuex'
export default {
    name:"Home",
    data() {
        return {
            msg:"this is Home"
        }
    },
    computed: {
        moduleOne(){
            // 这里使用了命名空间
            return this.$store.state.moduleOne.moduleOnevalue
        },
        moduleTwo(){
            return this.$store.state.moduleTwo.moduleTwovalue
        },
        ...mapState({
           moduleOnevalue:(state)=>state.moduleOne.moduleOnevalue,
           moduleTwovalue:(state)=>state.moduleTwo.moduleTwovalue
        })
    },
    methods: {
 
    },
    mounted() {

    },
}
</script>

更多请见:http://www.mark-to-win.com/tutorial/50759.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值