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

Router-Link跳转同命名路由时页面不刷新问题求助

Vue路由同组件切换参数页面不刷新的解决方案

问题原因

当跳转同一路由组件(如ArticleDetail)仅变更params参数时,Vue为了性能优化不会重新挂载组件,因此onMounted钩子只会执行一次,导致页面内容未更新。

解决方法

方法1:监听路由参数变化

在ArticleDetail组件中,通过监听route.params.id的变化,触发重新获取数据的逻辑:

import { watch, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'

const route = useRoute()
const articleData = ref(null)

// 封装获取文章数据的函数
const fetchArticle = async (id) => {
  try {
    const response = await axios.get(`/api/article/${id}/`)
    articleData.value = response.data
  } catch (error) {
    console.log(error)
  }
}

// 初始加载数据
onMounted(() => {
  fetchArticle(route.params.id)
})

// 监听路由id变化,重新获取数据
watch(() => route.params.id, (newId) => {
  fetchArticle(newId)
})

方法2:给<router-view>添加key属性

在父组件的<router-view>上绑定key为$route.fullPath,强制每次路由变更时重新渲染组件:

<router-view :key="$route.fullPath"></router-view>

这样每次路由参数变化,组件都会重新挂载,onMounted钩子会再次执行,自动重新获取数据。

方法3:使用onBeforeRouteUpdate导航守卫

在ArticleDetail组件中,利用路由守卫在路由更新前重新获取数据:

import { onMounted, ref, onBeforeRouteUpdate } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'

const route = useRoute()
const articleData = ref(null)

const fetchArticle = async (id) => {
  try {
    const response = await axios.get(`/api/article/${id}/`)
    articleData.value = response.data
  } catch (error) {
    console.log(error)
  }
}

onMounted(() => {
  fetchArticle(route.params.id)
})

// 路由更新前触发
onBeforeRouteUpdate((to) => {
  fetchArticle(to.params.id)
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:10:06