如何在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}
},

轉載自:https://blog.csdn.net/qq_32917123/article/details/80898439?utm_source=copy

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章