路由路径包含将被提取到 beforeRouteEnter 中的数据

Route path contain data that would be fetched into beforeRouteEnter

在我的路由器中有一个动态路由,我需要在从 beforeRouteEnter

中的存储调用中获取数据后设置其路径的最后一部分
beforeRouteEnter (to, from, next) {
if(to.params.categoryId) {
  next(vm => {
    store.dispatch('getSearchResults', to.params)
      .then(res => {
        let category = res.data.categories.find(cat => cat.id == to.params.categoryId);
        to.params.CName = category.name;
        // to.path = to.path + `/${category.name}`;
        console.log(to)
      }).catch(err => false)
  })
}else next();

路线:

{
  path: 'directory/bc-:categoryId(\d+)?/:CName?',
  name: 'SearchResults',
  component: () => import(/* webpackChunkName: "listing" */ '../views/SearchResults.vue')
},

我需要从数据中将Route中的CName改成category.name,这样路由最终会在Id

之后显示分类名称

您应该使用包含 2 个子节点的路由 - 一个将分派 Vuex 操作,然后转到另一个子节点。

{
  path: 'directory/bc-:categoryId(\d+)?',
  name: 'SearchResultsParent',
  redirect:
  {
    name: 'SearchResultsFetch',
  },
  component: WrapperComponent,
  children:
  [
    {
      path: '',
      name: 'SearchResultsFetch',
      component: FetchSearchResults,
    },
    {
      path: ':CName',
      name: 'SearchResultsList',
      component: ShowSearchResults,
    },
  ]
}
// WrapperComponent.vue
<template>
  ....
  <router-view />
  ....
</template>
// FetchSearchResults.vue
<script>
export default
{
  created()
  {
    this.fetchData();
  },
  beforeRouteUpdate(to, from, next)
  {
    this.fetchData();
    next();
  },
  methods:
  {
    fetchData()
    {
      store.dispatch('getSearchResults', this.$route.params)
      .then(res => {
        let category = res.data.categories.find(cat => cat.id == this.route.params.categoryId);
        this.$router.push({
          name: 'SearchResultsList',
          params:
          {
            categoryId: this.$route.params.categoryId,
            CName: category.name,
          }
        });
      }).catch(err => false)
    }
  }
}