我如何在 Vue-router 上返回/路由-返回?

好吧,简单地解释一下:

我有三页纸。

  • 第一页(主页)
  • 第二页(菜单)
  • 第三页(关于)

第一页有..

<router-link to="/menu">

按钮,当单击路由到“/菜单”。

目前,第2页(菜单)有一个

<router-link to="/">

按钮,当这个按钮被点击它恢复到以前的位置”/“第1页(主页)。

但是我不想为每个页面创建一个路由器组件来“返回”到上一个页面(好像我有100个页面,这可能是很多工作路由回来)。有没有办法用 Vue-router 实现这一点?类似于 window.history.back()

我很想知道有没有办法,因为我在文件里找不到。

先谢谢你,约翰

207355 次浏览

You can use Programmatic Navigation. In order to go back, you use this:

router.go(n)

Where n can be positive or negative (to go back). This is the same as history.back().So you can have your element like this:

<a @click="$router.go(-1)">back</a>

If you're using Vuex you can use https://github.com/vuejs/vuex-router-sync

Just initialize it in your main file with:

import VuexRouterSync from 'vuex-router-sync';
VuexRouterSync.sync(store, router);

Each route change will update route state object in Vuex. You can next create getter to use the from Object in route state or just use the state (better is to use getters, but it's other story https://vuex.vuejs.org/en/getters.html), so in short it would be (inside components methods/values):

this.$store.state.route.from.fullPath

You can also just place it in <router-link> component:

<router-link :to="{ path: $store.state.route.from.fullPath }">
Back
</router-link>

So when you use code above, link to previous path would be dynamically generated.

Another solution is using vue-router-back-mixin

import BackMixin from `vue-router-back-mixin`


export default {
...
mixins: [BackMixin],
methods() {
goBack() {
this.backMixin_handleBack()
}
}
...
}

This works like a clock for me:

methods: {
hasHistory () { return window.history.length > 2 }
}

Then, in the template:

<button
type="button"
@click="hasHistory()
? $router.go(-1)
: $router.push('/')" class="my-5 btn btn-outline-success">&laquo;
Back
</button>

Use $router.back() directly to go back/route-back programmatic on vue-router. Or if in the template of the component use router.back().

This answer to this question becomes much trickier if you're coding a mobile app as you now need an integrated solution that accommodates back history from either your UI back button OR the "back" button provided by the mobile device!

Frameworks like Ionic and Quasar can intercept mobile device back button events. Quasar handles these events for you and adapts behaviour for desktop and mobile platform builds so a for example a Cordova/Capacitor mobile app build will ensure that a "back" action can intelligently either close a dialog or go back a page or even close the app!

If you want to do this in Nuxt, this method worked for me

<nuxt-link :to="`${this.$nuxt.context.from.path}`" class="m-0 float-right btn btn-sm btn-sm btn-info">
<i class="bi bi-plus-lg"></i> \{\{ $t('back') }}
</nuxt-link>

Worked for me, short and practical. (Nuxt.js)

<a @click="$router.back()"></>