VUE——ルーティング検証と対応するブロックの使用

26545 ワード

前言
Webプロジェクトでは、ログインの有無に応じてルーティングの検証と対応するブロックが必要になることが多い.
ログイン情報の保存
まず、vuexのstoreです.jsには、次のような保存ログイン状態が書かれています.
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: false
  },
  mutations: {
    //   
    login (state, user) {
      state.user = user
    },
    //   
    logout (state, user) {
      state.user = false
    }
  }
})

ルーティング検証
利用するbeforeEach( (to, from, next) => { }
フック関数beforeEachの3つのパラメータの意味:1 to:間もなく入るターゲットのルーティングオブジェクト.②from:現在のナビゲーションが離れるルーティングオブジェクト.③next:このメソッドを呼び出すと、次のフックに入る.next(’/経路’)ある経路を指定する
ルーティング検証例1:次のホップのルーティングは'/watchHouse'または'/AgentMsg'であり,ログインしていなければコードnext({path:'/login’})を介してログインのインタフェースにジャンプする.
コードは次のとおりです.
if (!store.state.user && (to.path === '/watchHouse' || to.path === '/AgentMsg')) {
  next({ path: '/login' })
}

ルーティング検証例2:ルーティング'/my'の下で、'/toolCompute'にジャンプし、ログインしていない場合はログインページにジャンプします.
コードは次のとおりです.
if (!store.state.user && (from.path === '/my') && (to.path === '/ToolCompute')) {
  next({ path: '/login' })
}

すべてのコード:いくつかのルーティングをルーティング検証する目的:次のルーティングが'/login'の場合next();ログインしておらず、次のルーティングが'/watchHouse'または'/AgentMsg'である場合、next({path:'/login'});現在のルーティングが'/my'で、次のルーティングが'/toolCompute'である場合、next({path:'/login'}).
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
  } elseif (!store.state.user && (to.path === '/watchHouse' || to.path === '/AgentMsg')) {
      next({ path: '/login' })
    } else {
      next()
    }
    elseif (!store.state.user && (from.path === '/my') && (to.path === '/ToolCompute')) {
      next({ path: '/login' })
    }
  }
})

もう1つの書き方:複数のページでルーティング検証が必要な場合はrouter/index.jsルーティング設定時、追加
meta: {
   requireAuth: true,  //      ,              
},

検証するだけです.meta.requireAuthはルーティング検証を行うことができます.
コードは以下の通りです:router/index.js
const router = new Router({
  routes: [{
  	path: '/', 
  	redirect: '/login'
  },{
  	path: '/login', 
  	name: 'login', 
  	component: login
  },{
    path: '/watchHouse', 
    name: 'watchHouse', 
    component: watchHouse
  },{
    path: '/AgentMsg', 
    name: 'AgentMsg', 
    component: AgentMsg, 
    meta: {
      requireAuth: true
    }
  },{
    path: '/my', 
    name: 'my', 
    component: my, 
    meta: {
      requireAuth: true
    }
  },{
    path: '/ToolCompute', 
    name: 'ToolCompute', 
    component: ToolCompute, 
    meta: {
      requireAuth: true
    }
  }]
})

目的:アクセスが必要なすべてのルーティングをルーティング検証する
/*      */
router.beforeEach((to, from, next) => {
  if(to.meta.requireAuth) {  //              
    if(localStorage.getItem('token')) {  // localStorage     token    
      next()
    }
    else {
      Message.error('     ');
      next({ path: '/login' })
    }
  }
  else {
    next()
  }
})

ルーティング検証の場所
ルーティング検証はvueインスタンスの位置順序と多少関係がある.ルーティング検証がVue()の後ろに書かれている場合、正常なページジャンプはまずルーティング検証を実行し、対応するページをジャンプします.しかし、ブラウザのアドレスバーにジャンプする完全なルーティング情報を直接入力すると、このルーティングジャンプは判断されません.
通常のコード:(main.js)
/*            */
/*      */
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
  } elseif (!store.state.user && (to.path === '/watchHouse' || to.path === '/AgentMsg')) {
      next({ path: '/login' })
    } else {
      next()
    }
    elseif (!store.state.user && (from.path === '/my') && (to.path === '/ToolCompute')) {
      next({ path: '/login' })
    }
  }
})

new Vue({
  render: h => h(App),
  router,
  store
}).$mount('#app')

レスポンスブロック
ルートインスタンスではcheckLogin()という方法でログイン情報の状態を判断し,ネットワークリクエストにログインタイムアウトが加わると応答ブロックを行う.
main.js
new Vue({
  render: h => h(App),
  router,
  store,
  created(){
    checkLogin().then(function (res) {
      if(res.data && res.data.code == 1){
        store.commit('login',true);
      }
      else{
        router.push('/watchHouse-css');
      }
    })
  }
}).$mount('#app')

/network/request.js
//     
axios.interceptors.response.use(function(res){
  //      
  if(res.data && res.data.code == 2){
    app.$alert('       ,     ', '  ', {
      confirmButtonText: '  ',
      type:'warning',
      closeOnClickModal:false,
      callback: action => {
        router.push('/watchHouse-css')
      }
    });
  }
  return res;
},function(err){
  return Promise.reject(err);
})