Home > Web Front-end > JS Tutorial > body text

How does Vue-Router implement middleware pipeline?

青灯夜游
Release: 2020-07-08 16:26:27
forward
2344 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 using Vue-Router.

What is a middleware pipeline?

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.

Start

First use Vue CLI to 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 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>
Copy after login

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

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

Create store

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 &#39;vue&#39;
import Vuex from &#39;vuex&#39;

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 #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.

Define routes

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

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

Only authenticated users can access

/dashboard. Otherwise users should be redirected to the /login route when accessing this route. We associate the auth middleware with this route.

Only authenticated and subscribed users can access

/dashboard/movies. The route is protected by isSubscribed and auth middleware.

Create Route

Next, create a

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 &#39;vue&#39;
import Router from &#39;vue-router&#39;
import store from &#39;../store&#39;

import Login from &#39;../components/Login&#39;
import Dashboard from &#39;../components/Dashboard&#39;
import Movies from &#39;../components/Movies&#39;


Vue.use(Router)

const router = new Router({
    mode: &#39;history&#39;,
    base: process.env.BASE_URL,
    routes: [
        {
            path: &#39;/login&#39;,
            name: &#39;login&#39;,
            component: Login
        },

        {
            path: &#39;/dashboard&#39;,
            name: &#39;dashboard&#39;,
            component: Dashboard,
            children: [{
                path: &#39;/dashboard/movies&#39;,
                name: &#39;dashboard.movies&#39;,
                component: Movies
            }
        ],
        }
    ]
})


export default router
Copy after login

Here we create a new

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.

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

src/main.js file with the following code:

import Vue from &#39;vue&#39;
import App from &#39;./App.vue&#39;
import router from &#39;./router/router&#39;
import store from &#39;./store&#39;

Vue.config.productionTip = false


new Vue({
  router,
  store,
  render: h => h(App),
}).$mount(&#39;#app&#39;)
Copy after login

Create middleware

Create a

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: &#39;dashboard&#39;
        })
    }
   
    return next()
   }
Copy after login

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

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

export default function auth ({ next, store }){
 if(!store.getters.auth.loggedIn){
     return next({
        name: &#39;login&#39;
     })
 }

 return next()
}
Copy after login

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

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

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

isSubscribed 中的中间件类似于 auth 中间件。我们用 store检查用户是否订阅。如果用户已订阅,那么他们可以访问预期路由,否则将其重定向回 dashboard 页面。

保护路由

现在已经创建了所有中间件,让我们利用它们来保护路由。使用以下代码编辑 src/router/router.js 文件:

import Vue from &#39;vue&#39;
import Router from &#39;vue-router&#39;
import store from &#39;../store&#39;

import Login from &#39;../components/Login&#39;
import Dashboard from &#39;../components/Dashboard&#39;
import Movies from &#39;../components/Movies&#39;

import guest from &#39;./middleware/guest&#39;
import auth from &#39;./middleware/auth&#39;
import isSubscribed from &#39;./middleware/isSubscribed&#39;

Vue.use(Router)

const router = new Router({
    mode: &#39;history&#39;,
    base: process.env.BASE_URL,
    routes: [{
            path: &#39;/login&#39;,
            name: &#39;login&#39;,
            component: Login,
            meta: {
                middleware: [
                    guest
                ]
            }
        },
        {
            path: &#39;/dashboard&#39;,
            name: &#39;dashboard&#39;,
            component: Dashboard,
            meta: {
                middleware: [
                    auth
                ]
            },
            children: [{
                path: &#39;/dashboard/movies&#39;,
                name: &#39;dashboard.movies&#39;,
                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, 然后传递 nextPipeline const。值得注意的是,middlewarePipeline 函数是一个递归函数,它将调用自身来获取下一个在堆栈中运行的中间件,同时将index增加为1。

把它们放在一起

让我们使用middlewarePipeline。像下面这段代码一样编辑 src/router/router.js 文件:

import Vue from &#39;vue&#39;
import Router from &#39;vue-router&#39;
import store from &#39;../store&#39;

import Login from &#39;../components/Login&#39;
import Dashboard from &#39;../components/Dashboard&#39;
import Movies from &#39;../components/Movies&#39;

import guest from &#39;./middleware/guest&#39;
import auth from &#39;./middleware/auth&#39;
import isSubscribed from &#39;./middleware/isSubscribed&#39;
import middlewarePipeline from &#39;./middlewarePipeline&#39;

Vue.use(Router)

const router = new Router({
    mode: &#39;history&#39;,
    base: process.env.BASE_URL,
    routes: [{
            path: &#39;/login&#39;,
            name: &#39;login&#39;,
            component: Login,
            meta: {
                middleware: [
                    guest
                ]
            }
        },
        {
            path: &#39;/dashboard&#39;,
            name: &#39;dashboard&#39;,
            component: Dashboard,
            meta: {
                middleware: [
                    auth
                ]
            },
            children: [{
                path: &#39;/dashboard/movies&#39;,
                name: &#39;dashboard.movies&#39;,
                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

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

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template