首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >VueX的模块你知道多少?

VueX的模块你知道多少?

作者头像
马克社区
发布2022-05-17 16:19:29
发布2022-05-17 16:19:29
3820
举报
文章被收录于专栏:高端IT高端IT

为什么会出现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’ }

代码语言:javascript
复制
},
moduleTwo:{
  state:{
    moduleTwovalue:'0'
  }
}
123456

} })

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

代码语言:javascript
复制
<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>
123456789101112131415161718192021222324252627282930313233343536373839

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

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档