5-vue中的路由攔截


登錄成功后

 

 

 此時的狀態管理中

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
      user: {
         name:window.localStorage.getItem('user'|| '[]')==null ? "未登錄":JSON.parse(window.localStorage.getItem('user' || '[]')).name,
         username:window.localStorage.getItem('user'|| '[]')==null ? "":JSON.parse(window.localStorage.getItem('user' || '[]')).username,
         userface:window.localStorage.getItem('user'|| '[]')==null ? "":JSON.parse(window.localStorage.getItem('user' || '[]')).userface,
         roles:window.localStorage.getItem('user'|| '[]')==null ? "":JSON.parse(window.localStorage.getItem('user' || '[]')).roles,
      }
    },
    mutations: {
      login (state,user) {
         state.user=user;
         window.localStorage.setItem('user',JSON.stringify(user));
      }
    }
  })

登錄和首頁

 

 

 路由守衛

router.beforeEach((to, from, next) => {
  
  if(to.name=='login'){ //如果是登錄頁直接放行
    next();
    return;
  }

  var name=store.state.user.name; //如果不是登錄頁,判斷用戶是否登錄

  if(name=="未登錄"){ //如果未登錄
    if(to.meta.requireAuth || to.name==null){ //判斷請求的是那個頁面
      next({path: '/', query: {redirect: to.path}}) //path:'/'是跳轉到/路徑,query后面的是重定向要去的路徑
    }else{
      next();
    }
  }else{
    next();
  }
})

當在瀏覽器地址欄中輸入\home時候如果沒登陸,跳轉到登錄頁面。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM