Typically, when building a SPA, certain routes need to be protected. For example, suppose we have a dashboard route that only allows authenticated users to access it. We can ensure that only legitimate users can access it by using auth middleware.
In this tutorial, we will learn how to implement middleware pipelines for Vue applications using Vue-Router.
Middleware pipeline is a bunch of different middleware that run in parallel with each other.
Continuing with the previous case, suppose there is another route on /dashboard/movies
that we only want subscribed users to have access to. We already know that to access the dashboard route, you need to authenticate. So how should the /dashboard/movies
route be protected to ensure that only authenticated and subscribed users have access? By using middleware pipelines, you can chain multiple middlewares together and ensure they run in parallel.
First use Vue CLI to quickly build a new Vue project.
vue create vue-middleware-pipeline
After creating and installing the project directory, switch to the newly created directory and run the following command from the terminal:
npm i vue-router vuex
Vue-router — is the official router of Vue.js
Vuex — is Vue’s state management library
Our program will contain three components.
Login — This component is displayed to users who have not yet authenticated.
Dashboard — This component is displayed to logged in users.
Movies — We will display this component to users who are logged in and have an active subscription.
Let's create these components. Change to the src/components
directory and create the following files: Dashboard.vue
, Login.vue
, and Movies.vue
Use the following code to edit the Login.vue
file:
<template> <div> <p>This is the Login component</p> </div> </template>
Use the following code to edit the Dashboard.vue
file:
<template> <div> <p>This is the Dashboard component for authenticated users</p> <router-view/> </div> </template>
Finally, add the following Code is added to the Movies.vue
file:
<template> <div> <p>This is the Movies component for authenticated and subscribed users</p> </div> </template>
As far as Vuex
is concerned, store is just a place to save the state of our program container. It allows us to determine if the user is authenticated and to check if the user is subscribed.
In the src folder, create a store.js
file and add the following code to the file:
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 contains a ## inside its state #user object. The
user object contains the
loggedIn and
isSubscribed properties, which help us determine if the user is logged in and has a valid subscription. We also define a
getter in the store to return the
user object.
/login is accessible to everyone except authenticated users. When an authenticated user accesses this route, it should be redirected to the dashboard route. This route should be accompanied by a
guest middleware.
/dashboard. Otherwise users should be redirected to the
/login route when accessing this route. We associate the
auth middleware with this route.
/dashboard/movies. The route is protected by
isSubscribed and
auth middleware.
router folder in the
src directory, and then create a
in that folder router.js file. Edit the file with the following code:
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
router instance, passing a few configuration options as well as a
routes attribute, which Accept all routes we defined previously. Please note that these routes are currently unprotected. We'll fix this soon.
src/main.js file with the following code:
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')
in the src/router
directory middleware folder, and then create
guest.js,
auth.js and
IsSubscribed.js files under this folder. Add the following code to the
guest.js file:
export default function guest ({ next, store }){ if(store.getters.auth.loggedIn){ return next({ name: 'dashboard' }) } return next() }
guest
中间件检查用户是否通过了身份验证。如果通过了身份验证就会被重定向到 dashboard
路径。
接下来,用以下代码编辑 auth.js
文件:
export default function auth ({ next, store }){ if(!store.getters.auth.loggedIn){ return next({ name: 'login' }) } return next() }
在 auth
中间件中,我们用 store
检查用户当前是否已经 authenticated
。根据用户是否已经登录,我们要么继续请求,要么将其重定向到登录页面。
使用以下代码编辑 isSubscribed.js
文件:
export default function isSubscribed ({ next, store }){ if(!store.getters.auth.isSubscribed){ return next({ name: 'dashboard' }) } return next() }
isSubscribed
中的中间件类似于 auth
中间件。我们用 store
检查用户是否订阅。如果用户已订阅,那么他们可以访问预期路由,否则将其重定向回 dashboard 页面。
现在已经创建了所有中间件,让我们利用它们来保护路由。使用以下代码编辑 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
在这里,我们导入了所有中间件,然后为每个路由定义了一个包含中间件数组的元字段。中间件数组包含我们希望与特定路由关联的所有中间件。
我们使用 Vue Router 提供的导航守卫来保护路由。这些导航守卫主要通过重定向或取消路由的方式来保护路由。
其中一个守卫是全局守卫,它通常是在触发路线之前调用的钩子。要注册一个全局的前卫,需要在 router
实例上定义一个 beforeEach
方法。
const router = new Router({ ... }) router.beforeEach((to, from, next) => { //necessary logic to resolve the hook })
beforeEach
方法接收三个参数:
to:
这是我们打算访问的路由。
from:
这是我们目前的路由。
next:
这是调用钩子的 function
。
使用 beforeEach
钩子可以运行我们的中间件。
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 }) })
我们首先检查当前正在处理的路由是否有一个包含 middleware
属性的元字段。如果找到 middleware
属性,就将它分配给 const
变量。接下来定义一个 context
对象,其中包含我们需要传递给每个中间件的所有内容。然后,把中间件数组中的第一个中间件做为函数去调用,同时传入 context
对象。
尝试访问 /dashboard
路由,你应该被重定向到 login
路由。这是因为 /src/store.js
中的 store.state.user.loggedIn
属性被设置为 false
。将 store.state.user.loggedIn
属性改为 true
,就应该能够访问 /dashboard
路由。
现在中间件正在运行,但这并不是我们想要的方式。我们的目标是实现一个管道,可以针对特定路径运行多个中间件。
return middleware[0]({ …context})
注意上面代码块中的这行代码,我们只调用从 meta
字段中的中间件数组传递的第一个中间件。那么我们怎样确保数组中包含的其他中间件(如果有的话)也被调用呢?这就是管道派上用场的地方。
切换到 src/router
目录,然后创建一个 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
有三个参数:
context:
这是我们之前创建的 context
对象,它可以传递给栈中的每个中间件。
middleware:
这是在 route
的 meta
字段上定义的middleware
数组本身。
index:
这是在 middleware
数组中运行的当前中间件的 index
。
const nextMiddleware = middleware[index] if(!nextMiddleware){ return context.next }
在这里,我们只是在传递给 middlewarePipeline
函数的 index
中拔出中间件。如果在 index
没有找到 middleware
,则返回默认的 next
回调。
return () => { const nextPipeline = middlewarePipeline( context, middleware, index + 1 ) nextMiddleware({ ...context, next: nextPipeline }) }
我们调用 nextMiddleware
来传递 context
, 然后传递 nextPipeline
const
。值得注意的是,middlewarePipeline
函数是一个递归函数,它将调用自身来获取下一个在堆栈中运行的中间件,同时将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>
来运行栈中包含的后续中间件。
return middleware[0]({ ...context, next: middlewarePipeline(context, middleware, 1) })
在调用第一个中间件之后,使用 middlewarePipeline
函数,还会调用栈中包含的后续中间件,直到不再有中间件可用。
如果你访问 /dashboard/movies
路由,应该被重定向到 /dashboard
。这是因为 user
当前是 authenticated
但没有有效订阅。如果将 store
中的 store.state.user.isSubscribed
属性设置为 true
,就应该可以访问 /dashboard/movies
路由了。
中间件是保护应用中不同路由的好方法。这是一个非常简单的实现,可以使用多个中间件来保护 Vue 应用中的单个路由。你可以在(https://github.com/Dotunj/vue...)找到所有的源码。
英文原文地址:https://blog.logrocket.com/vue-middleware-pipelines/
为了保证的可读性,本文采用意译而非直译。
The above is the detailed content of How does Vue-Router implement middleware pipeline?. For more information, please follow other related articles on the PHP Chinese website!