javascript - Vue路由器不路由到指定位置

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

我将 vue 与 vue-router 一起使用,当路由到子路由时路由不起作用。

  {
    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>

最佳答案

为“/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

关于javascript - Vue路由器不路由到指定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62255911/

相关文章:

javascript - 循环设置内部 HTML

javascript - 合并具有相同第一个键值的对象,因此其余键值将添加到合并对象中

vue.js - 没有缓存的 VueJs 计算属性

vue.js - Vue.js 中的嵌套组件 : Failed to mount component: template or render function not defined

javascript - supabaseUrl 是必需的 sveltekit

javascript - Bootstrap/Laravel 不会加载 JavaScript

javascript - 当您在 Ember 函数上绑定(bind) 'this' 时会发生什么?

javascript - 去抖动内部开关盒内的 RegExp 不起作用

javascript - vue.js/javascript新建对象onclick,其中一个值为你点击的列表项的值

javascript - 如何使用 v-for 使用 vue.js 渲染表格