如何在vue中判断用户是否登录,登录权限

首先给大家推荐一下我老师大神的人工智能教学网站。教学不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵黄段子!点这里可以跳转到网站

首先需要新建一个store文件夹,新建index.js   、 

main.js中引入store

将状态信息保存至localStorage中

import Vue from 'vue'import Vuex from 'vuex' Vue.use(Vuex)const key = 'user'const isLogin = 'isLogin'const store = new Vuex.Store({  state () {    return {      user: null,      isLogin: '0'    }  },  getters: {    getStorage: function (state) {      if (!state.user) {        state.user = JSON.parse(localStorage.getItem(key))        state.isLogin = localStorage.getItem(isLogin)      }      return state.user    }  },  mutations: {    $_setLogin (state, value) {      state.isLogin = value      localStorage.setItem(isLogin, value)    },    $_setStorage (state, value) {      state.user = value      localStorage.setItem(key, JSON.stringify(value))    },    $_removeStorage (state) {      state.user = null      localStorage.removeItem(key)    }  }}) export default store

然后在main.js

router.beforeEach((to, from, next) => {  if (to.matched.some(m => m.meta.auth)) {    if (window.localStorage.isLogin === '1') {      next()    } else if (to.path !== '/') {      next({path: '/login'})      Vue.prototype.$message.warning('检测到您还未登录,请登录后操作!')    }  } else {    next()  }})

在组件中表单验证成功后,点击按钮时:

this.$message({  message: '登录成功',  type: 'success'})this.$store.commit('$_setStorage', {user: this.loginForm.username})this.$store.commit('$_setLogin', '1')this.$router.push({name: 'Home'})

前提是需要在router中添加meta: {auth: true}

{    path: '/',    component: Login,    name: 'Login',    meta: {auth: true}},

点这里可以跳转到人工智能网站

发表评论