Vue-router声明式回退实现咨询:router-link与router.go(n)用法疑问
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.
Why Your Original router-link Setup Fails
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
1. Hybrid router-link + Click Event
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="#"givesrouter-linka valid placeholder target@click.preventstops 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>
3. Pure Programmatic Navigation (No 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

