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

Nuxt3组件setup脚本路由异常:nuxt-link跳转后路由未更新

Nuxt3组件setup中路由更新异常问题

我在Nuxt3组件的setup脚本中使用路由及其参数时遇到问题:通过nuxt-link跳转后,目标组件setup脚本里获取到的路由仍是跳转前的旧路由。我期望无论通过浏览器直接访问还是nuxt-link跳转,test组件显示的完整路径都为/test,但实际仅在直接访问或页面刷新时路由才正确。

复现步骤

  • 执行初始化命令:npx nuxi init test
  • 进入项目目录:cd test
  • 安装依赖:npm i

相关文件代码

/app.vue

<template>
  <div>
    <router-view></router-view>
  </div>
</template>

/pages/index.vue

<template>
    <h1>index</h1>
    <nuxt-link to="/test">to test</nuxt-link>
</template>

/pages/test.vue

<template>
    <h1>test</h1>
    <p>Path: {{ fullPath }}</p>
</template>

<script setup lang="ts">
const fullPath = useRoute().fullPath;
console.log(fullPath);
</script>

问题原因与解决方案

原因

你直接将useRoute()返回对象的fullPath属性赋值给了普通常量,这个赋值仅在组件初始化时执行一次。而Nuxt3的客户端路由跳转过程中,组件初始化时路由状态尚未完成更新,因此拿到的是跳转前的旧路由值。

解决方法

方法1:使用计算属性(推荐)

通过Vue的计算属性实时绑定路由的fullPath,确保路由变化时自动更新值:

<template>
    <h1>test</h1>
    <p>Path: {{ fullPath }}</p>
</template>

<script setup lang="ts">
const route = useRoute();
const fullPath = computed(() => route.fullPath);

// 若需打印实时路径,可结合watch
watch(fullPath, (newPath) => {
  console.log(newPath);
}, { immediate: true });
</script>

方法2:监听路由变化

通过watch监听整个路由对象,在路由更新时手动更新路径值:

<template>
    <h1>test</h1>
    <p>Path: {{ fullPath }}</p>
</template>

<script setup lang="ts">
const route = useRoute();
const fullPath = ref(route.fullPath);

watch(route, (newRoute) => {
  fullPath.value = newRoute.fullPath;
  console.log(newRoute.fullPath);
}, { immediate: true });
</script>

关键说明

useRoute()返回的是响应式路由对象,但直接提取其属性赋值给普通变量会丢失响应性。必须通过计算属性或监听的方式,才能在客户端导航时获取到实时更新的路由信息。

内容的提问来源于stack exchange,提问作者Laurin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:32:47