You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt中使用to指令跳转至动态路由

How to Use Dynamic 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:

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 :to binding 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:56:10