做的产品证书管理系统使用的是VueJs和ElementUI,现将遇到的一些知识点记录一下。

VUe全局变量的实现

全局变量专用模块Global.vue是以一个特定模块来组织管理全局变量,需要引用的地方导入该模块即可。使用方法如下:
将全局变量模块挂载到Vue.prototype里,在程序入口的main.js里加下面代码:

import Global from '../components/Global.vue'
Vue.prototype.global = Global

挂载后,在需要引用全局变量的模块时,不需要再导入全局变量模块,直接用this引用即可。 如:this.global.notifySuccess()

Vue的全局请求拦截器

在全局变量专用模块Global.vue中设置全局Vue请求拦截器,以在全局拦截器中添加请求超时的方法为例,若请求超时则取消此次请求,并提示用户。请求超时设置通过拦截器Vue.http.interceptors实现具体代码如下:

 Vue.http.interceptors.push((request,next) => {
   let timeout
   // 如果某个请求设置了_timeout,那么超过该时间,该终端会(abort)请求,并执行请求设置的钩子函数onTimeout方法,不会执行then方法。
   if (request._timeout) {
     timeout = setTimeout(() =>{
       if (request.onTimeout) {
         request.onTimeout(request)
         request.abort()
         }
       }, request._timeout)
   }
   next((response) => {
     clearTimeout(timeout)
     return response
     })
 })

当页面中用到vue-resource请求的地方设置如下即可:

this.$http.get('url',{
        params:{.......},
        ......
        _timeout:3000,
        onTimeout: (request) => {
           alert("请求超时");
       }
    }).then((response)=>{
});

Vue的全局守卫

全局路由守卫是指在路由跳转时对登录状态进行检查。可以使用router.beforeEach注册一个全局前置守卫:

const router = new VueRouter({…})
Router.beforeEach((to,from,next)=> { …})

当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫resolve完之前一直处于等待中。每个守卫方法接收三个参数:
to:Route即将要进入的目标,即路由对象;
from:Route当前导航正要离开的路由;
next:Function:一定要调用该方法来resolve这个钩子。执行效果依赖next方法的调用参数。
使用实例如下:

// 全局路由守卫,路由时检查用户是否登录,若无登录信息,指向登录界面
router.beforeEach((to, from, next) => {
    const nextRoute = ['AdminIndex','系统设置', '产品管理', '客户管理', '证书管理', '日志管理']
    if (nextRoute.indexOf(to.name)>= 0) {
        if (sessionStorage.getItem('username')){
            next()
        } else {
            window.location.replace('/login.html')
        }
    } else {
      next()
    }
})

蓝胖子tracer
7 声望1 粉丝

人生没有白走的路,每一步都算数!