如何在 Nuxt js 中使用命名路由?

时间:2020-12-19 03:01:10

标签: vue.js nuxt.js vue-router

问题

当路由嵌套时,如何以用户身份在 Nuxt 中以编程方式导航?我知道我可以使用 const toggleDoneTask = (id) => { setTaskItems(taskItems => { let taskItemsCopy = [...taskItems].map((task) => ({ ...task })) let newItems = taskItemsCopy.map((t) => { if (t.id === id) { t.done = !t.done }; return t; }) localStorage.setItem('tasks', JSON.stringify(newItems)) return newItems }) } 将用户推送到交换页面,但是当路由嵌套时,我不知道该怎么做。如果我使用 this.$router.push({ name: "exchanges" })this.$router.push({ path: "exchanges/create" }),即使我已经在当前 URL 中,“exchanges/create”也会添加到 URL 中。

此外,页面组件名称是“ExchangesPage”、“EachExchangePage”、“CreateExchangePage”和“HomePage”。当我尝试将其用作命名路由的名称时,这不起作用。

./pages 中的当前文件结构

this.$router.push("exchanges/create")

2 个答案:

答案 0 :(得分:5)

要快速检查您在 nuxt 项目中的路线,您可以这样做:

在您的项目目录中导航到:

.nuxt/router.js

这是包含由 nuxt 生成的所有路由的文件,您可以检查它们的确切名称以导航到它们,请看这张图片:

enter image description here

根据上图来自我的一个项目,我可以这样做:

this.$router.push({ name: 'universities-id' });

答案 1 :(得分:3)

基于 docs,嵌套路由的名称将是:

pages/
--| exchanges/
-----| _userId/
--------| index.vue             // name: 'exchanges-userId'
-----| create/
--------| index.vue             // name: 'exchanges-create'
--| index.vue

示例脚本用法:

this.$router.push({ name: 'exchanges-userId', params: { userId: 11 } })
this.$router.push({ name: 'exchanges-create' })

模板用法示例:

<nuxt-link :to="{ name: 'exchanges-userId', params: { userId: 11 } }">User 11</nuxt-link>
<nuxt-link :to="{ name: 'exchanges-create' }">Create</nuxt-link>