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>

 

更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/119116711

posted @ 2022-05-13 18:39  忘川信使  阅读(60)  评论(0编辑  收藏  举报