作的產品證書管理系統使用的是VueJs和ElementUI,現將遇到的一些知識點記錄一下。html
全局變量專用模塊Global.vue是以一個特定模塊來組織管理全局變量,須要引用的地方導入該模塊便可。使用方法以下:
將全局變量模塊掛載到Vue.prototype裏,在程序入口的main.js里加下面代碼:vue
import Global from '../components/Global.vue' Vue.prototype.global = Global
掛載後,在須要引用全局變量的模塊時,不須要再導入全局變量模塊,直接用this引用便可。 如:this.global.notifySuccess()session
在全局變量專用模塊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)=>{ });
全局路由守衛是指在路由跳轉時對登陸狀態進行檢查。能夠使用router.beforeEach註冊一個全局前置守衛:vue-resource
const router = new VueRouter({…}) Router.beforeEach((to,from,next)=> { …})
當一個導航觸發時,全局前置守衛按照建立順序調用。守衛是異步解析執行,此時導航在全部守衛resolve完以前一直處於等待中。每一個守衛方法接收三個參數:
to:Route即將要進入的目標,即路由對象;
from:Route當前導航正要離開的路由;
next:Function:必定要調用該方法來resolve這個鉤子。執行效果依賴next方法的調用參數。
使用實例以下:this
// 全局路由守衛,路由時檢查用戶是否登陸,若無登陸信息,指向登陸界面 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() } })