做的產品證書管理系統使用的是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完之前一直處于等待中。每個守衛方法接收三個參數:
使用實例如下:
// 全局路由守衛,路由時檢查用戶是否登錄,若無登錄信息,指向登錄界面 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() } })
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com