A
A
Andy Oker2021-08-18 13:35:46
Vue.js
Andy Oker, 2021-08-18 13:35:46

How to form routes with asynchronous data?

I have a router.js file in which I set routes, for example, Main and Category:

import Vue from 'vue'
import VueRouter from 'vue-router'
const routes = [
 {
    path: '/',
    name: 'Main',
    component: () => import('./views/Main.vue'),
  },
  {
    path: '/category',
    name: 'Category',
    component: () => import('./views/Category.vue'),
  }
]


There is also a createRouter function:
export function createRouter() {
  const router = new VueRouter({
    scrollBehavior() {
      return { x: 0, y: 0 }
    },
    mode: 'history',
    routes
  })
  router.beforeEach((to, from, next) => {
    document.title = to.meta.title
    next()
  })
  return router
}


Before exporting the createdRouter function, I want to get all the categories in the following way: and for the route of the categories in the routes array, determine the path from their names: How can this be done?
store.dispatch('categories')
path: '/(cat1|cat2|cat3)/

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Klein Maximus, 2021-08-18
@Ashlis

Use dynamic routing and process the received ID - https://router.vuejs.org/en/guide/essentials/dynam...

const routes = [
 {
    path: '/',
    name: 'Main',
    component: () => import('./views/Main.vue'),
  },
  {
    path: '/category',
    name: 'Category',
    component: () => import('./views/Category.vue'),
  },
  {
    path: '/:category',
    // ...
  }
]

Accordingly, when receiving a request, look in the api for the presence of the :category category. If not, show a 404 error.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question