1.定義路由的時(shí)候配置meta屬性,requireAuth用來(lái)標(biāo)記跳轉(zhuǎn)的這個(gè)路由是否需要檢測(cè)登錄
下面的兩個(gè)頁(yè)面,登錄頁(yè)不需要檢測(cè),首頁(yè)需要檢測(cè)
const routers = [{   path: '/',   component: App,   children: [    {     path: '/login',     component: Login,   meta: {    title: '登錄'   }   },   {     path: '/home',     component: Home,   meta: {    title: '首頁(yè)',    requireAuth: true   }   }  ]}]export default routers2.main.js
返回遍歷的某個(gè)路由對(duì)象,我們定義為record,檢測(cè)這個(gè)對(duì)象是否擁有meta這個(gè)對(duì)象,如果有meta這個(gè)對(duì)象,檢測(cè)meta對(duì)象是不是有requireAuth這個(gè)屬性且為true
檢測(cè)到需要登錄權(quán)限后,我的做法是請(qǐng)求接口判斷用戶是否登錄
如果未登錄,跳轉(zhuǎn)到登錄頁(yè)面;如果已經(jīng)登錄,確保要調(diào)用next()方法,否則鉤子就不會(huì)被resolved
router.beforeEach((to, from, next) => { /* 頁(yè)面title */ if (to.meta.title) {  document.title = to.meta.title } /* 判斷該路由是否需要登錄權(quán)限 */ if (to.matched.some(record => record.meta.requireAuth)) {  //是否登錄  axios.post('/home/user/isLogin')    .then(function (response) {      if (response.data.code == 0) {        //未登錄        if (response.data.data.online == 0) {          next({            path: '/login',          })        } else {          //已登錄          next()        }      }    })    .catch(function (error) {      // Toast(error.data.msg);    }); } next();})以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長(zhǎng)站。
新聞熱點(diǎn)
疑難解答
圖片精選