Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Vue Middleware Pipeline

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "how to use Vue Middleware Pipeline", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Vue Middleware Pipeline how to use" article.

What is a middleware pipeline?

Middleware pipes (middleware pipeline) are a bunch of different middleware that run in parallel with each other.

Continuing the previous case, assuming there is another route on / dashboard/movies, we only want subscribers to access it. We already know that to access dashboard routing, you need to authenticate. So how do you secure the / dashboard/movies route to ensure that only authenticated and subscribed users can access it? By using middleware pipes, you can link multiple middleware together and ensure that they can run in parallel.

Start

First use Vue CLI [2] to quickly build a new Vue project.

Vue create vue-middleware-pipeline installation dependency

After creating and installing the project directory, change to the newly created directory and run the following command from the terminal:

Npm i vue-router vuex

Vue-router [3]-is the official router for Vue.js

Vuex [4]-is the state management library for Vue

Create a component

Our program will contain three components.

Login  -  this component is shown to users who have not yet been authenticated.

Dashboard  -this component is shown to logged-in users.

Movies  -  We will display this component to users who are logged in and have valid subscriptions.

Let's create these components. Change to the src/components directory and create the following files: Dashboard.vue, Login.vue, and Movies.vue

Edit the Login.vue file using the following code:

This is the Login component

Edit the Dashboard.vue file using the following code:

This is the Dashboard component for authenticated users

Finally, add the following code to the Movies.vue file:

This is the Movies component for authenticated and subscribed users

Create store

As far as Vuex is concerned, store is just a container for storing the state of our program. It allows us to determine whether the user is authenticated and to check whether 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 user object in its state. The user object contains loggedIn and isSubscribed properties, which help us determine whether the user is logged in and has a valid subscription. We also define a getter in store to return the user object.

Define rout

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

Everyone can access / login except those who are authenticated. When authenticated users access 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 redirect to the / login route when accessing this route. We associate auth middleware with this route.

Only authenticated and subscribed users can access / dashboard/movies. This route is protected by isSubscribed and auth middleware.

Create a rout

Next, create a router folder in the src directory, and then create a router.js file in that folder. Use the following code to edit the file:

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

Here, we create a new router instance, passing several configuration options and a routes property that accepts all the routes we defined earlier. Note that these routes are currently unprotected. We will solve the problem soon.

Next, route and store are injected into the Vue instance. Edit the src/main.js file using the following code:

Import Vue from 'vue'import App from'. / App.vue'import router from'. / router/router'import store from'. / store'Vue.config.productionTip = falsenew Vue ({router, store, render: h = > h (App),}). $mount ('# app') create middleware

Create a middleware folder in the src/router directory, and then create 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: 'dashboard'})} return next ()}

Guest middleware checks whether the user is authenticated. If authenticated, it 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: 'login'})} return next ()}

In auth middleware, we use store to check whether the user is currently authenticated. Depending on whether the user is logged in, we can either continue the request or redirect it to the login page.

Edit the isSubscribed.js file using the following code:

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

Middleware in isSubscribed is similar to auth middleware. We use store to check whether users subscribe. If the user is subscribed, they can access the expected route or redirect it back to the dashboard page.

Secure rout

Now that all the middleware has been created, let's use them to secure routing. Edit the src/router/router.js file using 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'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

Here, we import all the middleware and then define a meta field containing an array of middleware for each route. The middleware array contains all the middleware that we want to associate with a particular route.

Vue routing navigation guard

We use the navigation guard [5] provided by Vue Router to protect the route. These navigation guards protect routes mainly by redirecting or canceling routes.

One of the guards is the global guard, which is usually the hook that is called before the route is triggered. To register as a global avant-garde, you need to define a beforeEach method on the router instance.

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

The beforeEach method receives three parameters:

To: this is the route we intend to access.

From: this is our current route.

Next: this is the function that invokes the hook.

Running middleware

Use the beforeEach hook to run our middleware.

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

We first check whether the route we are currently working on has a meta field that contains the middleware attribute. If the middleware property is found, it is assigned to the const variable. Next, define a context object that contains everything we need to pass to each middleware. Then, the first middleware in the middleware array is called as a function, passing in the context object.

Try to access the / dashboard route, you should be redirected to the login route. This is because the store.state.user.loggedIn property in / src/store.js is set to false. Change the store.state.user.loggedIn attribute to true and you should be able to access the / dashboard route.

The middleware is running now, but this is not the way we want it to be. Our goal is to implement a pipeline that can run multiple middleware against a specific path.

Return middleware [0] ({... Context} "0")

Notice this line of code in the code block above, we only call the first middleware passed from the array of middleware in the meta field. So how do we make sure that other middleware (if any) contained in the array is also called? This is where pipes come in handy.

Create Pip

Change to the src/router directory and create a middlewarePipeline.js file. Add the following code to the file:

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 has three parameters:

Context: this is the context object we created earlier, which can be passed to each middleware in the stack.

Middleware: this is the middleware array itself defined on the meta field of route.

Index: this is the index of the current middleware running in the middleware array.

Const nextMiddleware = return context.next [index] if (! nextMiddleware) {return context.next}

Here, we just pull out the middleware in the index passed to the middlewarePipeline function. If no middleware is found in index, the default next callback is returned.

Return () = > {const nextPipeline = middlewarePipeline (context, middleware, index + 1) nextMiddleware ({... context, next: nextPipeline})}

We call nextMiddleware to pass context, and then pass nextPipeline const. It is worth noting that the middlewarePipeline function is a recursive function that calls itself to get the next middleware running on the stack while increasing index to 1.

Put them together.

Let's use middlewarePipeline. Edit the src/router/router.js file like 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'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

Here, we use middlewarePipeline to run the subsequent middleware contained in the stack.

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

After the first middleware is called, the middlewarePipeline function is used, and the subsequent middleware contained in the stack is called until no more middleware is available.

If you visit the / dashboard/movies route, it should be redirected to / dashboard. This is because user is currently an 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.

The above is about the content of this article on "how to use the Vue middleware pipeline". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report