Home >Web Front-end >Vue.js >Learn more about Vue's middleware pipeline

Learn more about Vue's middleware pipeline

青灯夜游
青灯夜游forward
2020-10-02 12:23:305062browse

Learn more about Vue's middleware pipeline

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 use Vue-Router to implement middleware pipelines for Vue applications.

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

Installing 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

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

Vuex — is Vue’s state management library

Create component

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>
  <p>
    <p>This is the Login component</p>
  </p>
</template>

Use the following code to edit the Dashboard.vue file:

<template>
  <p>
    <p>This is the Dashboard component for authenticated users</p>
    <router-view/>
  </p>
</template>

Finally, add the following Code added to the Movies.vue file:

<template>
  <p>
    <p>This is the Movies component for authenticated and subscribed users</p>
  </p>
</template>

Create store

As far as Vuex is concerned, store is just a A container to hold the state of our program. 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
        }
    }
})

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 a route

Next, create a

router folder in the src directory, and then in that folder Create a router.js file in . 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

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;)

Create middleware

in the

src/router directory Create a middleware folder, and then create the guest.js, auth.js and IsSubscribed.js files under that 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()
   }

guest The middleware checks whether the user is authenticated. If the authentication is passed, you will be redirected to the dashboard path.

Next, edit the

auth.js file with the following code:

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

 return next()
}

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

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

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

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

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

Vue 路由导航守卫

我们使用 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: 这是在 routemeta 字段上定义的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 &#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

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

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

在调用第一个中间件之后,使用 middlewarePipeline 函数,还会调用栈中包含的后续中间件,直到不再有中间件可用。

If you access the /dashboard/movies route, you should be redirected to /dashboard. This is because user is currently authenticated but does not have a valid subscription. If you set the store.state.user.isSubscribed property in store to true, you should be able to access the /dashboard/movies route .

Conclusion

Middleware is a great way to protect different routes in your application. This is a very simple implementation that can use multiple middlewares to protect a single route in a Vue application. You can find all source code at (https://github.com/Dotunj/vue-middleware-pipelines).

Related recommendations:

2020 front-end vue interview questions summary (with answers)

vue tutorial Recommended: The latest 5 vue.js video tutorial selections in 2020

For more programming-related knowledge, please visit:Introduction to Programming! !

The above is the detailed content of Learn more about Vue's middleware pipeline. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:logrocket.com. If there is any infringement, please contact admin@php.cn delete