如何在Nuxt中使用to指令跳转至动态路由
to Values for Routing in Nuxt with Table Rows Hey there! Let's get that cleaner routing syntax working for you. The issue with your second approach is that nuxt isn't a valid directive you can attach directly to a <tr> element—Nuxt's official routing tool is the <nuxt-link> component, and we just need to tweak how we use it with table rows.
Here's the best solution to get that dynamic :to binding working while keeping your code clean:
Use <nuxt-link> with the tag Property
Nuxt's <nuxt-link> component supports a tag prop that lets you specify what HTML element it should render as. This is perfect for table rows, since it lets you keep the semantic table structure while adding routing functionality.
Your code would look like this:
<nuxt-link v-for="item in favourites.slice(0, 5)" :key="item.id" :to="`/items/${item.id}`" tag="tr" > <!-- Your table data cells go here --> <td>{{ item.name }}</td> <td>{{ item.description }}</td> </nuxt-link>
This works because:
- The
tag="tr"tells<nuxt-link>to render as a table row instead of the default<a>tag, which avoids HTML validation issues (since<a>can't wrap<tr>directly). - The
:tobinding works exactly as you expected—you can use template literals or computed properties to pass dynamic routes. - You get all the benefits of
<nuxt-link>like prefetching (if enabled) and proper route navigation without full page reloads.
Alternative: Keep Using @click (But Simplify It)
If you prefer to stick with your original approach for any reason, you can still make it a bit cleaner by extracting the navigation logic to a method:
<!-- In your template --> <tr v-for="item in favourites.slice(0, 5)" :key="item.id" @click="navigateToItem(item)" > <!-- In your script --> methods: { navigateToItem(item) { this.$router.push(`/items/${item.id}`) } }
But the <nuxt-link> with tag prop is definitely the more idiomatic Nuxt way to handle this scenario.
内容的提问来源于stack exchange,提问作者ptrckdev

