@darion
In Vue.js 3, you can implement multiple middlewares by using the composition API and Vue Router. Here's an example of how you can do it:
1
|
npm install vue-router@next |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import { createRouter, createWebHistory } from 'vue-router' import Home from './views/Home.vue' import Dashboard from './views/Dashboard.vue' // Import your middlewares import middleware1 from './middlewares/middleware1' import middleware2 from './middlewares/middleware2' // Create the router instance const router = createRouter({ history: createWebHistory(), routes: [ { path: '/', component: Home, beforeEnter: middleware1, // Apply middleware1 to this route }, { path: '/dashboard', component: Dashboard, beforeEnter: [middleware1, middleware2], // Apply both middleware1 and middleware2 to this route }, ], }) export default router |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// middleware1.js export default function middleware1(to, from, next) { // Implement your middleware logic here console.log('middleware1') next() } // middleware2.js export default function middleware2(to, from, next) { // Implement your middleware logic here console.log('middleware2') next() } |
1 2 3 4 5 |
import { createApp } from 'vue' import App from './App.vue' import router from './router' createApp(App).use(router).mount('#app') |
With this setup, each time a route is navigated to, the corresponding middleware function(s) will be executed before the route component is rendered. Note that the next
function is called to proceed to the next middleware or to the route itself.
You can add as many middlewares as you need by supplying an array of middleware functions in the beforeEnter
property of the route configuration.