How does Vue-Router implement middleware pipeline?

青灯夜游
Release: 2020-07-08 16:26:27
forward
2245 people have browsed it

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.

How does Vue-Router implement middleware pipeline?

In this tutorial, we will learn how to implement middleware pipelines for Vue applications usingVue-Router.

What is a middleware pipeline?

Middleware pipelineis a bunch of different middleware that run in parallel with each other.

Continuing with the previous case, suppose there is another route on/dashboard/moviesthat 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/moviesroute 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.

Start

First useVue CLIto quickly build a new Vue project.

vue create vue-middleware-pipeline
Copy after login

Install dependencies

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
Copy after login

Vue-router— is the official router of Vue.js

Vuex— is Vue’s state management library

Create components

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 thesrc/componentsdirectory and create the following files:Dashboard.vue,Login.vue, andMovies.vue

Use the following code to edit theLogin.vuefile:

Copy after login

Use the following code to edit theDashboard.vuefile:

Copy after login

Finally, add the following Code is added to theMovies.vuefile:

Copy after login

Create store

As far asVuexis 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 astore.jsfile 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 } } })
Copy after login

store contains a ## inside its state #userobject. Theuserobject contains theloggedInandisSubscribedproperties, which help us determine if the user is logged in and has a valid subscription. We also define agetterin the store to return theuserobject.

Define routes

Before creating routes, you should define them and associate the corresponding middleware that will be attached to them.

/loginis 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 aguestmiddleware.

Only authenticated users can access

/dashboard. Otherwise users should be redirected to the/loginroute when accessing this route. We associate theauthmiddleware with this route.

Only authenticated and subscribed users can access

/dashboard/movies. The route is protected byisSubscribedandauthmiddleware.

Create Route

Next, create a

routerfolder in thesrcdirectory, and then create ain that folder router.jsfile. 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
Copy after login

Here we create a new

routerinstance, passing a few configuration options as well as aroutesattribute, which Accept all routes we defined previously. Please note that these routes are currently unprotected. We'll fix this soon.

Next, inject routing and store into the Vue instance. Edit the

src/main.jsfile 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')
Copy after login

Create middleware

Create a

in thesrc/routerdirectory middlewarefolder, and then createguest.js,auth.jsandIsSubscribed.jsfiles under this folder. Add the following code to theguest.jsfile:

export default function guest ({ next, store }){ if(store.getters.auth.loggedIn){ return next({ name: 'dashboard' }) } return next() }
Copy after login

guest中间件检查用户是否通过了身份验证。如果通过了身份验证就会被重定向到dashboard路径。

接下来,用以下代码编辑auth.js文件:

export default function auth ({ next, store }){ if(!store.getters.auth.loggedIn){ return next({ name: 'login' }) } return next() }
Copy after login

auth中间件中,我们用store检查用户当前是否已经authenticated。根据用户是否已经登录,我们要么继续请求,要么将其重定向到登录页面。

使用以下代码编辑isSubscribed.js文件:

export default function isSubscribed ({ next, store }){ if(!store.getters.auth.isSubscribed){ return next({ name: 'dashboard' }) } return next() }
Copy after login

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
Copy after login

在这里,我们导入了所有中间件,然后为每个路由定义了一个包含中间件数组的元字段。中间件数组包含我们希望与特定路由关联的所有中间件。

Vue 路由导航守卫

我们使用 Vue Router 提供的导航守卫来保护路由。这些导航守卫主要通过重定向或取消路由的方式来保护路由。

其中一个守卫是全局守卫,它通常是在触发路线之前调用的钩子。要注册一个全局的前卫,需要在router实例上定义一个beforeEach方法。

const router = new Router({ ... }) router.beforeEach((to, from, next) => { //necessary logic to resolve the hook })
Copy after login

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 }) })
Copy after login

我们首先检查当前正在处理的路由是否有一个包含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})
Copy after login

注意上面代码块中的这行代码,我们只调用从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
Copy after login

middlewarePipeline有三个参数:

context:这是我们之前创建的context对象,它可以传递给栈中的每个中间件。

middleware:这是在routemeta字段上定义的middleware数组本身。

index:这是在middleware数组中运行的当前中间件的index

const nextMiddleware = middleware[index] if(!nextMiddleware){ return context.next }
Copy after login

在这里,我们只是在传递给middlewarePipeline函数的index中拔出中间件。如果在index没有找到middleware,则返回默认的next回调。

return () => { const nextPipeline = middlewarePipeline( context, middleware, index + 1 ) nextMiddleware({ ...context, next: nextPipeline }) }
Copy after login

我们调用nextMiddleware来传递context, 然后传递nextPipelineconst。值得注意的是,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
Copy after login

在这里,我们使用 middlewarePipeline 来运行栈中包含的后续中间件。

return middleware[0]({ ...context, next: middlewarePipeline(context, middleware, 1) })
Copy after login

在调用第一个中间件之后,使用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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn