您好,登錄后才能下訂單哦!
如何在nuxt中使用路由守衛(wèi)?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
1.在plugins文件下創(chuàng)建一個route.js
import { getCookie, setCookie } from '@/pages/logreg/api/cookie' import axios from 'axios' export default ({ app, store }) => { app.router.beforeEach((to, from, next) => { let isClient = process.client if (isClient) { let currentUrl = location.href if (currentUrl.indexOf('access_token=') !== -1) { let wechattoken = currentUrl.split('access_token=')[1] wechattoken = wechattoken.split('&')[0] setCookie('token', wechattoken, 5) } let token = getCookie('token') if (token) { store.state.user.userinfo.token = token axios .get('https://api.ass.net/pub/api/user_info', { params: { token } }) .then(res => { res = res.data if (res.code == 0) { res = res.data res.headImg = res.headImg.replace('http:', 'https:') store.state.user.userinfo = Object.assign( {}, store.state.user.userinfo, res ) } }) .catch(error => console.log(error)) } } next() }) }
2.在nuxt.config.js里面配置
plugins: [ { src: '@/plugins/route', ssr: true } ],
PS:Nuxt在axios請求攔截中使用路由
最近在開發(fā)一個網(wǎng)站,用的nuxt搭建的框架,因為需要在請求token過期之后提示用戶重新登錄并且返回登錄頁面,但是在axios的配置文件中使用router.push一直報錯,都準(zhǔn)備放棄使用公眾組件去進(jìn)行路由跳轉(zhuǎn)了,但是天無絕人之路,最終在官方文檔中找到了redirect,具體操作如下:
在axios的js文件中添加默認(rèn)的方法,并且獲取redirect,并且使用使用myredirect將redirect儲存起來
let myredirect; export default function ({redirect }) { myredirect = redirect; }
在需要使用路由跳轉(zhuǎn)的地方進(jìn)行跳轉(zhuǎn)(此處在判斷token過期時跳轉(zhuǎn))
if (error.message.toString().slice(-3) === '401') { Vue.prototype.$message.error('登陸超時,請重新登陸...') setTimeout(function () { return myredirect('/login/login') }, 2000) }
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。