【问题标题】:Vue router doesn't route to specified locationVue路由器没有路由到指定位置
【发布时间】:2020-09-27 01:19:14
【问题描述】:

我正在使用带有 vue-router 的 vue,并且路由在路由到子路由时不起作用。

  {
    path: '/user',
    name: 'User',
    component: User,
    children: [
      {
        path: 'profile',
        component: Profile,
      },
    ],
  }

以编程方式路由到 /user/profile

<template>
    <div>
            <button @click="goToUserProfile()">create new</button>
    </div>
</template>

<script>

export default {
  methods: {
    goToUserProfile() {
      this.$router.push('/user/profile')    // Routing doesn't work
       .catch(console.log);
    },
  },
};
</script>

【问题讨论】:

  • 错误是什么(如果有)?你试过这个。$router.push({name: 'whatever you name your route'}) ?
  • 当我使用 this.$router.push('/user/profile');没有抛出错误,但是当我使用 this.$route.push({name: '/user/profile'});抛出错误'[vue-router] 名为'/user/profile'的路由不存在'
  • 检查您的路线并查看您的路线的名称属性
  • 您可以尝试将name: 'UserProfile' 添加到嵌套路由中,然后像this.$router.push({ name: 'UserProfile' }); 一样对UserProfile 进行编程导航
  • 现在抛出的错误显示“NavigationDuplicated”

标签: javascript vue.js vuejs2 vue-component vue-router


【解决方案1】:

为“/user/profile”指定一个路由名称“Profile”

  {
    path: '/user',
    name: 'User',
    component: User,
    children: [
      {
        path: 'profile',
        name: "Profile",
        component: Profile,
      },
    ],
  }

导航使用路线名称

this.$router.push({name: "Profile"});

你的用户组件应该这样声明

用户.vue

<template>
<div>
    <p>this is user component</p>
    <!-- your Profile component will replace this route-view -->
    <route-view /> 
</div>
</template>

演示

https://codesandbox.io/s/falling-bash-6dl7m

【讨论】:

  • 现在抛出的错误显示“NavigationDuplicated”
  • 因为您已经在这条路线中,您可以从其他路线导航到“个人资料”路线
  • 如果我将配置文件路由声明为父容器(即不在子容器中),那么它可以正常工作。但我希望个人资料成为子路线。
【解决方案2】:

确保将&lt;router-view&gt;&lt;/router-view&gt; 放入用户组件模板中以显示嵌套(子)路由。

<template>
    <div>
        <button @click="goToUserProfile()">create new</button>
        <router-view></router-view>   <!-- placeholder for children routes -->
    </div> 
</template> 

然后你可以同时访问 this.$router.push('/user/profile')this.$router.push({ name: 'UserProfile' })

正如 Vue 路由器文档所述: 要将组件渲染到这个嵌套插座中,我们需要使用 VueRouter 中的 children 选项。

https://router.vuejs.org/guide/essentials/nested-routes.html

希望对您有所帮助。

【讨论】:

  • 我没有为嵌套路由添加 。这就是为什么 URL 更改但组件不呈现的原因。谢谢
猜你喜欢
  • 2021-02-08
  • 2022-01-14
  • 2019-04-10
  • 2022-01-24
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 2018-10-31
  • 2017-01-23
相关资源
最近更新 更多