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

Vue-router声明式回退实现咨询:router-link与router.go(n)用法疑问

How to Implement Page Back Navigation with Vue Router (Declarative & Hybrid Approaches)

Hey there! I see you’re trying to use router-link to trigger a page back action and hit a snag where :to="$router.go(-1)" doesn’t work. Let’s break down why this happens and walk through the right ways to handle it.

The :to prop of router-link expects either a string route path (like "/home") or a route object (like { name: 'Home' }) that points to a specific, predefined route. But $router.go(-1) is a method that executes back navigation immediately—it doesn’t return a valid route value for the :to prop. That’s why your component doesn’t behave as expected.

Correct Solutions for Back Navigation

You can keep using router-link (for its built-in accessibility features and component structure) by binding a click event to trigger back navigation, while overriding the default router-link behavior:

<router-link 
  to="#" 
  @click.prevent="$router.go(-1)" 
  tag="h1"
>
  Go Back
</router-link>
  • to="#" gives router-link a valid placeholder target
  • @click.prevent stops the default anchor tag jump behavior
  • $router.go(-1) executes the back navigation, just like your working plain <h1> example

2. Shorthand with $router.back()

Vue Router includes $router.back() as a shorthand for $router.go(-1)—it does the exact same thing (navigates back one step in the browser history stack). You can swap it in for cleaner code:

<router-link 
  to="#" 
  @click.prevent="$router.back()" 
  tag="h1"
>
  Go Back
</router-link>

If you don’t need router-link’s extra features (like active route styling), your original approach is totally valid and straightforward:

<h1 @click="$router.go(-1)">Go Back</h1>

Quick Note for Vue 3 Composition API

If you’re using Vue 3 with the Composition API, you can access the router instance directly in your script:

import { useRouter } from 'vue-router'

const router = useRouter()
const goBack = () => router.go(-1)

Then use it in your template:

<router-link to="#" @click.prevent="goBack" tag="h1">Go Back</router-link>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:52:27