1

在我的路由器中有一个动态路由,在从 beforeRouteEnter 中的 store 调用中获取数据后,我需要设置其路径的最后一部分

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 之后显示类别名称

4

1 回答 1

0

您应该使用带有 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)
    }
  }
}
于 2021-05-06T10:40:17.960 回答