Vue——vue3中vuex模块化管理(一般写法、命名空间写法、辅助函数写法)

src\store\index.js 配置文件: 引入user模块

import { createStore } from 'vuex'
import user from './user'
export default createStore({
  // 设置全局数据
  state: {
   
  },
  // 计算属性
  getters: {
   
  },
  // 修改状态方法(同步)
  mutations: {
    
  },
  // 修改状态方法(异步)
  actions: {
    
  },
  modules: {
    user
  }
})

src\store\user.js 配置文件


const user = {
    // 命名空间写法这个一定要加上,非常重要
    namespaced: true,
    state: () => ({
        username: 'abc',
        age: 10
    }),
    mutations: {
        setUserName (state) {
            state.username = 'ddd'
        },
        setAge (state, value) {
            state.age = value
        }
    },
    actions: {
        asyncSetAge (context, value = 50) {
            console.log(context, 'context');
            setTimeout(() => {
                context.commit('setAge', value)
            }, 200);
        }
    },
    getters: {
        descrption (state, getters, rootState) {
            return state.username + '年龄是' + state.age + '岁'

        }
    }
}

export default user

一般写法:

demo.vue文件

<template>
    <h1>用户名:{{$store.state.user.username}}</h1>
    <h1>描述:{{$store.getters.descrption}}</h1>
    <button @click="changeAge">异步修改年龄</button>
</template>
<script>

export default {

    mounted () {
        console.log(this.$store);
    },
    methods: {
        changeAge () {
             this.$store.dispatch('asyncSetAge')
           
        },

    }
}
</script>

命名空间写法

demo.vue文件

<template>
      <!-- 命名空间的写法 -->
    <h1>用户名:{{$store.state.user.username}}</h1>
    <h1>描述:{{$store.getters['user/descrption']}}</h1>
    <button @click="changeAge">异步修改年龄</button>

</template>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
    computed: {
        ...mapState(['user']),
        ...mapGetters('user', ['descrption'])
    },
    mounted () {
        console.log(this.$store);
    },
    methods: {
        changeAge () {
            // 命名空间写法
            this.$store.dispatch('user/asyncSetAge')
        },
    }
}
</script>

辅助函数写法

demo.vue文件

<template>
    <!-- 辅助函数的写法 -->
    <h1>用户名:{{user.username}}</h1>
    <h1>描述:{{descrption}}</h1>
    <button @click="asyncSetAge(100)">异步修改年龄100</button>
</template>
<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
    computed: {
        ...mapState(['user']),
        ...mapGetters('user', ['descrption'])
    },
    mounted () {
        console.log(this.$store);
    },
    methods: {
       
        // 辅助函数的写法
        ...mapActions('user', ['asyncSetAge'])
    }
}
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值