vue中路由验证和相应拦截的使用详解

2019-11-16,,,

在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
 }
 }
})

路由验证:       

      路由验证用  router.beforeEach( (to, from, next) => {  } 
      这里的to代表要去的路由指向,from是指从哪个路由跳转过来的,next是判断操作,如果为空,表示放行。
      比如:下一跳的路由为‘/watchHouse'或者‘/AgentMsg' ,如果没有登录的话,通过代码 next ({path: '/login'})

跳转到登录的界面。代码如下:

if (!store.state.user && (to.path === '/watchHouse' || to.path === '/AgentMsg')) {
 next({ path: '/login' })
}

比如:在路由‘/my'下,要跳往 ‘/ToolCompute',如果没有登录的话,跳转到登录页面。代码如下:    

if (!store.state.user && (from.path === '/my') && (to.path === '/ToolCompute')) {
 next({ path: '/login' })
}

全部代码:

router.beforeEach((to, from, next) => {
 if (to.path === '/login') {
 next()
 } else {
 if (!store.state.user && (to.path === '/watchHouse' || to.path === '/AgentMsg')) {
  next({ path: '/login' })
 } else {
  next()
 }
 if (!store.state.user && (from.path === '/my') && (to.path === '/ToolCompute')) {
  next({ path: '/login' })
 }
 }
})

需要注意的是,路由验证这个方法函数与vue实例的顺序还有关系。如果写在vue()的后面,下面就会执行,后判断。

如下图所示:

这样写,当然是可以执行的路由跳转判断的,但是当我们直接在浏览器的地址栏里直接输入我们要跳转的

完整路由信息的时候,这个路由跳转就不会被判断了。如下图所示:

如果把路由验证写到VUE实例的前面,就不会出现这样的问题了,这样就会先进行路由判断,再进行执行实例里边的内容了。

代码顺序如下所示:

响应拦截:比如在根实例中通过checkLogin()这个方法去判断,登录信息 的状态,加入登录超时,则进行响应拦截,代码如下。

var app=new Vue({
 el: '#app',
 router,
 store,
 created(){
 checkLogin().then(function (res) {
  if(res.data&&res.data.code==1){
  store.commit('login',true);
  }
  else{
  router.push('/watchHouse-css');
  }
 })
 },
 template: '<App/>',
 components: { App }
})


//响应拦截器
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);
}) 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

您可能感兴趣的文章:

  • VueJs路由跳转——vue-router的使用详解
  • Vue.js路由组件vue-router使用方法详解
  • vue-router:嵌套路由的使用方法
  • 详解vue2路由vue-router配置(懒加载)
  • Vue+axios 实现http拦截及路由拦截实例
  • 详解vue嵌套路由-params传递参数
  • vue-router路由简单案例介绍
  • vue使用watch 观察路由变化,重新获取内容
  • vue2笔记 — vue-router路由懒加载的实现
  • Vue.js:使用Vue-Router 2实现路由功能介绍

《vue中路由验证和相应拦截的使用详解.doc》

下载本文的Word格式文档,以方便收藏与打印。