使用模块化思想编写一个Vuex的登录模块

1.src/store/user.js

import Vue from 'vue'
export const USER_SIGIN = 'USER_SIGIN' //登录成功
export const USER_SIGOUT = 'USER_SIGOUT' //推出登录

export default({
    state: JSON.parse(sessionStorage.getItem('user')) || {},
    mutations: {
        [USER_SIGIN](state, user){
            sessionStorage.setItem('user', JSON.stringify(user))
            Object.assign(state, user);
        },
        [USER_SIGOUT](state){
            sessionStorage.removeItem('user')
            Object.keys(state).forEach(k => Vue.delete(state, k))
        }
    },
    actions: {
        [USER_SIGIN]({commit},user){
            commit(USER_SIGIN,user)
        },
        [USER_SIGOUT]({commit}){
            commit(USER_SIGOUT)
        }
    }
})

2.src/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import user from './user'

Vue.use(Vuex)

export default new Vuex.Store({
    strict: process.env.NODE_ENV !='production',//在生产环境下,使用严格模式
    modules:{
        user
    }
})

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Vuex模块结构可以更好地组织和管理应用程序的状态。以下是使用Vuex模块的步骤: 1. 创建一个模块对象,包含该模块的状态、mutation、action和getter: ```javascript const myModule = { state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { doubleCount (state) { return state.count * 2 } } } ``` 2. 在store中注册模块使用`modules`选项: ```javascript import Vuex from 'vuex' const store = new Vuex.Store({ modules: { myModule } }) ``` 3. 在组件中使用模块的状态、mutation、action和getter: ```javascript import { mapState, mapMutations, mapActions, mapGetters } from 'vuex' export default { computed: { // 获取模块状态 ...mapState({ count: state => state.myModule.count }), // 获取模块的getter ...mapGetters('myModule', { doubleCount: 'doubleCount' }) }, methods: { // 触发模块的mutation ...mapMutations('myModule', { increment: 'increment' }), // 触发模块的action ...mapActions('myModule', { incrementAsync: 'incrementAsync' }) } } ``` 在上面的示例中,我们使用`mapState`、`mapMutations`、`mapActions`和`mapGetters`辅助函数来访问模块的状态、mutation、action和getter。这些辅助函数会自动将模块的名称添加到对应的方法名中,以便正确地访问模块。这样,我们就可以在组件中使用模块的状态和方法,而无需手动编写长长的命名空间前缀。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值