一篇文章學(xué)會(huì)Vue中間件管道
通常,在構(gòu)建SPA時(shí),需要保護(hù)某些路由。例如假設(shè)有一個(gè)只允許經(jīng)過(guò)身份驗(yàn)證的用戶訪問(wèn)的 dashboard 路由,我們可以通過(guò)使用 auth 中間件來(lái)確保合法用戶才能訪問(wèn)它。
在本教程中,我們將學(xué)到怎樣用 Vue-Router[1] 為Vue應(yīng)用程序?qū)崿F(xiàn)中間件管道。
什么是中間件管道?
中間件管道(middleware pipeline) 是一堆彼此并行運(yùn)行的不同的中間件。
繼續(xù)前面的案例,假設(shè)在 /dashboard/movies 上有另一個(gè)路由,我們只希望訂閱用戶可以訪問(wèn)。我們已經(jīng)知道要訪問(wèn) dashboard 路由,你需要進(jìn)行身份驗(yàn)證。那么應(yīng)該怎樣保護(hù) /dashboard/movies 路由以確保只有經(jīng)過(guò)身份驗(yàn)證和訂閱的用戶才能訪問(wèn)呢?通過(guò)使用中間件管道,可以將多個(gè)中間件鏈接在一起并確保它們能夠并行運(yùn)行。
開(kāi)始
首先用 Vue CLI[2] 快速構(gòu)建一個(gè)新的 Vue 項(xiàng)目。
vue create vue-middleware-pipeline
安裝依賴項(xiàng)
創(chuàng)建并安裝項(xiàng)目目錄后,切換到新創(chuàng)建的目錄并從終端運(yùn)行以下命令:
npm i vue-router vuex
Vue-router[3] — 是Vue.js的官方路由器
Vuex[4] — 是 Vue 的狀態(tài)管理庫(kù)
創(chuàng)建組件
我們的程序?qū)齻€(gè)組件。
Login — 此組件展示給尚未通過(guò)身份驗(yàn)證的用戶。
Dashboard — 此組件展示給已登錄的用戶。
Movies — 我們會(huì)向已登錄并擁有有效訂閱的用戶顯示此組件。
讓我們創(chuàng)建這些組件。切換到 src/components 目錄并創(chuàng)建以下文件:Dashboard.vue、Login.vue和Movies.vue
使用以下代碼編輯 Login.vue 文件:
<template>
<div>
<p>This is the Login component</p>
</div>
</template>
使用以下代碼編輯 Dashboard.vue 文件:
<template>
<div>
<p>This is the Dashboard component for authenticated users</p>
<router-view/>
</div>
</template>
最后,將以下代碼添加到 Movies.vue 文件中:
<template>
<div>
<p>This is the Movies component for authenticated and subscribed users</p>
</div>
</template>
創(chuàng)建store
就 Vuex 而言,store 只是一個(gè)用于保存我們程序狀態(tài)的容器。它允許我們確定用戶是否經(jīng)過(guò)身份驗(yàn)證以及檢查用戶是否已訂閱。
在 src 文件夾中,創(chuàng)建一個(gè) store.js 文件并將以下代碼添加到該文件中:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
user: {
loggedIn: false,
isSubscribed: false
}
},
getters: {
auth(state) {
return state.user
}
}
})
store 在其 狀態(tài) 內(nèi)包含一個(gè) user 對(duì)象。user 對(duì)象包含 loggedIn 和 isSubscribed 屬性,它可以幫助我們確定用戶是否已登錄并具有有效訂閱。我們還在 store 中定義了一個(gè) getter 來(lái)返回 user 對(duì)象。
定義路由
在創(chuàng)建路由之前,應(yīng)該先定義它們,并關(guān)聯(lián)將要附加到其上的對(duì)應(yīng)的中間件。
除了通過(guò)身份驗(yàn)證的用戶之外,每個(gè)人都可以訪問(wèn) /login。當(dāng)通過(guò)身份驗(yàn)證的用戶訪問(wèn)此路由時(shí),應(yīng)重定向到 dashboard 路由。這條路由應(yīng)該附有一個(gè) guest 中間件。
只有通過(guò)身份驗(yàn)證的用戶才能訪問(wèn) /dashboard。否則用戶在訪問(wèn)此路由時(shí)應(yīng)重定向到 /login 路由。我們把 auth 中間件與此路由相關(guān)聯(lián)。
只有通過(guò)身份驗(yàn)并訂閱的用戶才能訪問(wèn) /dashboard/movies。該路由受到 isSubscribed和 auth 中間件的保護(hù)。
創(chuàng)建路由
接下來(lái),在 src 目錄中創(chuàng)建一 個(gè)router 文件夾,然后在該文件夾中創(chuàng)建一個(gè) router.js 文件。使用以下代碼編輯文件:
import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
import Login from '../components/Login'
import Dashboard from '../components/Dashboard'
import Movies from '../components/Movies'
Vue.use(Router)
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
children: [{
path: '/dashboard/movies',
name: 'dashboard.movies',
component: Movies
}
],
}
]
})
export default router
在這里,我們創(chuàng)建了一個(gè)新的 router 實(shí)例,同時(shí)傳遞了幾個(gè)配置選項(xiàng)以及一個(gè) routes 屬性,它接受我們之前定義的所有路由。要注意目前這些路由還都是不受保護(hù)的。我們很快就會(huì)解決這個(gè)問(wèn)題。
接下來(lái)將路由和 store 注入Vue 實(shí)例。使用以下代碼編輯 src/main.js 文件:
import Vue from 'vue'
import App from './App.vue'
import router from './router/router'
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
創(chuàng)建中間件
在 src/router 目錄中創(chuàng)建一個(gè) middleware 文件夾,然后在該文件夾下創(chuàng)建 guest.js,auth.js和IsSubscribed.js文件。將以下代碼添加到 guest.js 文件中:
export default function guest ({ next, store }){
if(store.getters.auth.loggedIn){
return next({
name: 'dashboard'
})
}
return next()
}
guest 中間件檢查用戶是否通過(guò)了身份驗(yàn)證。如果通過(guò)了身份驗(yàn)證就會(huì)被重定向到 dashboard 路徑。
接下來(lái),用以下代碼編輯 auth.js 文件:
export default function auth ({ next, store }){
if(!store.getters.auth.loggedIn){
return next({
name: 'login'
})
}
return next()
}
在 auth 中間件中,我們用 store 檢查用戶當(dāng)前是否已經(jīng) authenticated。根據(jù)用戶是否已經(jīng)登錄,我們要么繼續(xù)請(qǐng)求,要么將其重定向到登錄頁(yè)面。
使用以下代碼編輯 isSubscribed.js 文件:
export default function isSubscribed ({ next, store }){
if(!store.getters.auth.isSubscribed){
return next({
name: 'dashboard'
})
}
return next()
}
isSubscribed 中的中間件類似于 auth 中間件。我們用 store檢查用戶是否訂閱。如果用戶已訂閱,那么他們可以訪問(wèn)預(yù)期路由,否則將其重定向回 dashboard 頁(yè)面。
保護(hù)路由
現(xiàn)在已經(jīng)創(chuàng)建了所有中間件,讓我們利用它們來(lái)保護(hù)路由。使用以下代碼編輯 src/router/router.js 文件:
import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
import Login from '../components/Login'
import Dashboard from '../components/Dashboard'
import Movies from '../components/Movies'
import guest from './middleware/guest'
import auth from './middleware/auth'
import isSubscribed from './middleware/isSubscribed'
Vue.use(Router)
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [{
path: '/login',
name: 'login',
component: Login,
meta: {
middleware: [
guest
]
}
},
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
meta: {
middleware: [
auth
]
},
children: [{
path: '/dashboard/movies',
name: 'dashboard.movies',
component: Movies,
meta: {
middleware: [
auth,
isSubscribed
]
}
}],
}
]
})
export default router
在這里,我們導(dǎo)入了所有中間件,然后為每個(gè)路由定義了一個(gè)包含中間件數(shù)組的元字段。中間件數(shù)組包含我們希望與特定路由關(guān)聯(lián)的所有中間件。
Vue 路由導(dǎo)航守衛(wèi)
我們使用 Vue Router 提供的導(dǎo)航守衛(wèi)[5]來(lái)保護(hù)路由。這些導(dǎo)航守衛(wèi)主要通過(guò)重定向或取消路由的方式來(lái)保護(hù)路由。
其中一個(gè)守衛(wèi)是全局守衛(wèi),它通常是在觸發(fā)路線之前調(diào)用的鉤子。要注冊(cè)一個(gè)全局的前衛(wèi),需要在 router 實(shí)例上定義一個(gè) beforeEach 方法。
const router = new Router({ ... })
router.beforeEach((to, from, next) => {
//necessary logic to resolve the hook
})
beforeEach 方法接收三個(gè)參數(shù):
to: 這是我們打算訪問(wèn)的路由。
from: 這是我們目前的路由。
next: 這是調(diào)用鉤子的 function。
運(yùn)行中間件
使用 beforeEach 鉤子可以運(yùn)行我們的中間件。
const router = new Router({ ...})
router.beforeEach((to, from, next) => {
if (!to.meta.middleware) {
return next()
}
const middleware = to.meta.middleware
const context = {
to,
from,
next,
store
}
return middleware[0]({
...context
})
})
我們首先檢查當(dāng)前正在處理的路由是否有一個(gè)包含 middleware 屬性的元字段。如果找到 middleware 屬性,就將它分配給 const 變量。接下來(lái)定義一個(gè) context 對(duì)象,其中包含我們需要傳遞給每個(gè)中間件的所有內(nèi)容。然后,把中間件數(shù)組中的第一個(gè)中間件做為函數(shù)去調(diào)用,同時(shí)傳入 context 對(duì)象。
嘗試訪問(wèn) /dashboard 路由,你應(yīng)該被重定向到 login 路由。這是因?yàn)?/src/store.js 中的 store.state.user.loggedIn 屬性被設(shè)置為 false。將 store.state.user.loggedIn 屬性改為 true,就應(yīng)該能夠訪問(wèn) /dashboard 路由。
現(xiàn)在中間件正在運(yùn)行,但這并不是我們想要的方式。我們的目標(biāo)是實(shí)現(xiàn)一個(gè)管道,可以針對(duì)特定路徑運(yùn)行多個(gè)中間件。
return middleware[0]({ …context} "0")
注意上面代碼塊中的這行代碼,我們只調(diào)用從 meta 字段中的中間件數(shù)組傳遞的第一個(gè)中間件。那么我們?cè)鯓哟_保數(shù)組中包含的其他中間件(如果有的話)也被調(diào)用呢?這就是管道派上用場(chǎng)的地方。
創(chuàng)建管道
切換到 src/router 目錄,然后創(chuàng)建一個(gè) middlewarePipeline.js 文件。將以下代碼添加到文件中:
function middlewarePipeline (context, middleware, index) {
const nextMiddleware = middleware[index]
if(!nextMiddleware){
return context.next
}
return () => {
const nextPipeline = middlewarePipeline(
context, middleware, index + 1
)
nextMiddleware({ ...context, next: nextPipeline })
}
}
export default middlewarePipeline
middlewarePipeline 有三個(gè)參數(shù):
context: 這是我們之前創(chuàng)建的 context 對(duì)象,它可以傳遞給棧中的每個(gè)中間件。
middleware: 這是在 route 的 meta 字段上定義的middleware 數(shù)組本身。
index: 這是在 middleware 數(shù)組中運(yùn)行的當(dāng)前中間件的 index。
const nextMiddleware = middleware[index]
if(!nextMiddleware){
return context.next
}
在這里,我們只是在傳遞給 middlewarePipeline 函數(shù)的 index 中拔出中間件。如果在 index 沒(méi)有找到 middleware,則返回默認(rèn)的 next 回調(diào)。
return () => {
const nextPipeline = middlewarePipeline(
context, middleware, index + 1
)
nextMiddleware({ ...context, next: nextPipeline })
}
我們調(diào)用 nextMiddleware 來(lái)傳遞 context, 然后傳遞 nextPipeline const。值得注意的是,middlewarePipeline 函數(shù)是一個(gè)遞歸函數(shù),它將調(diào)用自身來(lái)獲取下一個(gè)在堆棧中運(yùn)行的中間件,同時(shí)將index增加為1。
把它們放在一起
讓我們使用middlewarePipeline。像下面這段代碼一樣編輯 src/router/router.js 文件:
import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
import Login from '../components/Login'
import Dashboard from '../components/Dashboard'
import Movies from '../components/Movies'
import guest from './middleware/guest'
import auth from './middleware/auth'
import isSubscribed from './middleware/isSubscribed'
import middlewarePipeline from './middlewarePipeline'
Vue.use(Router)
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [{
path: '/login',
name: 'login',
component: Login,
meta: {
middleware: [
guest
]
}
},
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
meta: {
middleware: [
auth
]
},
children: [{
path: '/dashboard/movies',
name: 'dashboard.movies',
component: Movies,
meta: {
middleware: [
auth,
isSubscribed
]
}
}],
}
]
})
router.beforeEach((to, from, next) => {
if (!to.meta.middleware) {
return next()
}
const middleware = to.meta.middleware
const context = {
to,
from,
next,
store
}
return middleware[0]({
...context,
next: middlewarePipeline(context, middleware, 1)
})
})
export default router
在這里,我們使用 <code> middlewarePipeline <code>來(lái)運(yùn)行棧中包含的后續(xù)中間件。
return middleware[0]({
...context,
next: middlewarePipeline(context, middleware, 1)
})
在調(diào)用第一個(gè)中間件之后,使用 middlewarePipeline 函數(shù),還會(huì)調(diào)用棧中包含的后續(xù)中間件,直到不再有中間件可用。
如果你訪問(wèn) /dashboard/movies 路由,應(yīng)該被重定向到 /dashboard。這是因?yàn)?user 當(dāng)前是 authenticated 但沒(méi)有有效訂閱。如果將 store 中的 store.state.user.isSubscribed 屬性設(shè)置為 true,就應(yīng)該可以訪問(wèn) /dashboard/movies 路由了。
總結(jié)
中間件是保護(hù)應(yīng)用中不同路由的好方法。這是一個(gè)非常簡(jiǎn)單的實(shí)現(xiàn),可以使用多個(gè)中間件來(lái)保護(hù) Vue 應(yīng)用中的單個(gè)路由。
到此這篇關(guān)于一篇文章學(xué)會(huì)Vue中間件管道的文章就介紹到這了,更多相關(guān)Vue中間件管道內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
Reference
[1]Vue-Router:https://router.vuejs.org/
[2]Vue CLI:https://cli.vuejs.org/
[3]Vue-router:https://github.com/vuejs/vue-router/
[4]Vuex:https://vuex.vuejs.org/
[5]導(dǎo)航守衛(wèi):https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards
相關(guān)文章
vue 項(xiàng)目接口管理的實(shí)現(xiàn)
在vue開(kāi)發(fā)中,會(huì)涉及到很多接口的處理,當(dāng)項(xiàng)目足夠大時(shí),就需要定義規(guī)范統(tǒng)一的接口,本文就來(lái)介紹一下vue 項(xiàng)目接口管理,具有一定的參考價(jià)值,感興趣的小伙伴可以一起來(lái)了解一下2019-01-01
Vue.js每天必學(xué)之過(guò)濾器與自定義過(guò)濾器
Vue.js每天必學(xué)之過(guò)濾器與自定義過(guò)濾器,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09
vue報(bào)錯(cuò)Failed to execute 'appendChild&apos
這篇文章主要為大家介紹了vue報(bào)錯(cuò)Failed to execute 'appendChild' on 'Node'解決方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
vue3+echarts實(shí)現(xiàn)漸變色環(huán)形圖過(guò)程
這篇文章主要介紹了vue3+echarts實(shí)現(xiàn)漸變色環(huán)形圖過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
超詳細(xì)圖解如何運(yùn)行vue項(xiàng)目
Vue是一套用于構(gòu)建用戶界面的漸進(jìn)式框架,它的核心庫(kù)只關(guān)注視圖層,易于上手,也便于與其他庫(kù)或已有項(xiàng)目整合,下面這篇文章主要給大家介紹了關(guān)于如何運(yùn)行vue項(xiàng)目的相關(guān)資料,需要的朋友可以參考下2023-05-05

