一、首先创建vuex,vuex基本结构如下图所示
image.png
- (1)state里面主要是定义在存储store里面的数据,,为了避免每次刷新页面vuex内容都会清空,所以state里面初始值直接使用本地仓库的值
export default {
UserInfo:localStorage.getItem('userInfo')
UserToken : localStorage.getItem('userToken')
};
- (2) index则是主要将上述三个js文件暴露出去,并且将vuex挂载在vue上
import Vue from 'vue';
import Vuex from 'vuex';
import state from './state';
import * as actions from './actions';
import * as mutations from './mutations';
Vue.use(Vuex);
export default new Vuex.Store({
state,
actions,
mutations
});
import Vue from 'vue';
import Vuex from 'vuex';
import state from './state';
import * as actions from './actions';
import * as mutations from './mutations';
Vue.use(Vuex);
export default new Vuex.Store({
state,
actions,
mutations
});
二、当触发登录操作时,代码如下,将在action定义的Login方法挂载在this上面。其中mapActions需要引入一下。然后将登陆过后用户的数据传入给Login。
import {mapActions} from 'vuex'
methods: {
...mapActions(['Login']),
onSubmit() {
const username = this.form.name
const password = this.form.password
this.http.post('user/loginAdmin',{username,password}).then(res => {
this.Login(res.data.data)
this.$router.push("/")
})
}
}
三、外部调用Login方法,Login方法再将数据传给mutations定义的方法。
export const Login = ({commit}, UserInfo) => {
commit('SaveUserInfo', UserInfo)
}
四、 mutations里面主要是接受action传过来的数据,并可以在里面做处理,如果传过来的UserInfo有值,那么我们将数据存储在state里面和localStorage,如果传过来的没有值,我们则存为空值。
export const SaveUserInfo = (state,UserInfo) => {
if(UserInfo){
state.UserInfo = UserInfo.user
state.UserToken = UserInfo.token
localStorage.setItem('userInfo',JSON.stringify(UserInfo.user))
localStorage.setItem('userToken',UserInfo.token)
}else if(UserInfo === null) {
localStorage.setItem('userInfo',null)
localStorage.setItem('userToken','')
state.UserInfo = null
state.UserToken = ''
}
}
五、在router中的index.js定义路由拦截器,来实现根据情况来跳转页面
//定义路由
const router = new Router({
routes: [
{
path: '/login',
name: 'login',
component: login
},
{
path: '/',
name: 'home',
component: home,
children: [
{
path: '/user',
name: 'user',
component: user
}
]
},
],
mode: 'history',
})
//拦截器
router.beforeEach((to,from,next)=>{
if(to.path === '/login'){
next()
} else {
let userInfo = localStorage.getItem("userInfo")
if(userInfo === 'null'){
next('/login');
}else{
next()
}
}
})
export default router
六、退出当前登录状态操作
exitUser(command) {
this.Login(null)
this.$router.push("/login")
}
七、我们一般登录后会在首页显示用户的名字或者头像,但这时候我们发现存在vuex里面的数据信息是字符串类型,那么这时候我们可以再computed里面取出vuex里面的数据,再进行判断。
computed: {
getUserInfo() {
const info = this.$store.state.UserInfo
const user = typeof info === "string" ? JSON.parse(this.$store.state.UserInfo) : info
return {...user}
}
},
网友评论