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

问题描述

在我的路由器中有一个动态路由,在从 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后面显示category名称

解决方法

你应该使用一个有 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)
    }
  }
}