赞
踩
子模块user.js结构
// 初始化的数据 const state = { loginState: localStorage.getItem('isLogin') || '', userId: localStorage.getItem('userId') || '', token: localStorage.getItem('token') || '' } // 执行的异步操作 const actions = {} // 唯一改变数据的方式 const mutations = { change_loginState (state, payload) { state.loginState = payload }, change_userId (state, payload) { state.userId = payload }, change_token (state, payload) { state.token = payload } } export default { namespaced: true, // 改变mutations,可以直接使用user/change_loginState state, actions, mutations }
主模块引用user.js子模块
import Vue from 'vue' import Vuex from 'vuex' import user from './modules/user.js' Vue.use(Vuex) export default new Vuex.Store({ state: { }, mutations: { }, actions: { }, modules: { //在modules下进行引入 user } })
this.$store.commit()
// 登录成功之后,修改状态管理器的状态
this.$store.commit('user/change_loginState', 'ok')
this.$store.commit('user/change_token', res.data.token)
this.$store.commit('user/change_userId', res.data.id)
// 状态管理器.状态.模块.属性
this.$store.state.user.loginState === 'ok'
this.$store.state.user.userId
import { mapState } from 'vuex'
// 固定写法,利用解构赋值,获取state中的loginState,userId
computed: {
...mapState({
loginState: state => state.user.loginState,
userId: state => state.user.userId
})
}
this.loginState
或this.userId
找到对应状态组件的导航守卫中无法使用this找到实例
import { mapMutations } from 'vuex'
methods: {
...mapMutations({
change_loginState: 'user/change_loginState',
change_userId: 'user/change_userId',
change_token: 'user/change_token'
})
}
// this.$store.commit('user/change_loginState', 'ok')
// this.$store.commit('user/change_token', res.data.token)
// this.$store.commit('user/change_userId', res.data.id)
this.change_loginState('ok')
this.change_token(res.data.token)
this.change_userId(res.data.id)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。