vue-router - 如何获取上一页 url?

vue-router - How to get previous page url?

我想获取 vue-router 中的上一页 link 或 url。像这样。怎么做?

const link = this.$router.getPrevLink(); // function is not exist?
this.$router.push(link);

近义词是this.$router.go(-1)

this.$router.go(-1);

vue-router 的所有 navigation guards 都接收前一个路由作为 from 参数 ..

Every guard function receives three arguments:

  • to: Route: the target Route Object being navigated to.

  • from: Route: the current route being navigated away from.

  • next: Function: this function must be called to resolve the hook. The action depends on the arguments provided to next

例如,您可以使用 beforeRouteEnter,一个组件内导航守卫,获取之前的路线并将其存储在您的数据中..

...
data() {
 return {
   ...
   prevRoute: null
 }
},
beforeRouteEnter(to, from, next) {
  next(vm => {
    vm.prevRoute = from
  })
},
...

然后可以用this.prevRoute.path得到前面的URL.

虽然 很棒,但 收到的路线并不总是历史上的路线 在 popstate 导航的情况下(也就是当用户单击后退时)按钮)。

因此,如果您使用 Vuex,这里有一段符合此行为的代码片段:

const store = new Vuex.Store({
  state: {
    routerHistory: [],
  },
});

const router = new VueRouter({
  mode: 'history',
  scrollBehavior(to, from, savedPosition) {
    const fromHistory = Boolean(savedPosition);

    if (fromHistory && store.state.routerHistory.length > 0) {
      store.state.routerHistory.splice(-1, 1);
    } else {
      store.state.routerHistory.push(from);
    }

    return savedPosition || { x: 0, y: 0 };
  },
});

实施后,您可以为商店内的上一条路线定义 getter:

const store = new Vuex.Store({
  // ...
  getters: {
    previousRoute: (state) => {
      const historyLen = state.routerHistory.length;
      if (historyLen == 0) return null;
      return state.routerHistory[historyLen - 1];
    },
  },
});

此代码使用 scrollBehavior 挂钩,如果它是 popstate 导航,它只会接收 savedPosition 参数。 感谢 Vuex,我们可以将所有路由存储在一个数组中(跨多个页面)。

要将其直接从 $router 对象中提取出来,请在您的计算或方法中使用它:

lastRouteName: function() {
  let returnVal = '';

  const routerStack = this.$router.history.stack;
  const idx = this.$router.history.index;

  if (idx > 0) {
    returnVal = routerStack[idx - 1].name;
  }

  return returnVal;
}

这将 return 路线名称,但您也可以 return .path 或任何其他 属性 如果您愿意。

要检查历史对象,请执行 console.log(this.$router.history);

如果先前的 url 不存在,此路由解决方案将退回到静态 url。

<template>
    <div>
        <router-link :to="prevRoutePath">Previous Page</router-link>
        <router-link to="/">Home Page</router-link>
    </div>
</template>

<script>
export default {
    beforeRouteEnter(to, from, next) {
        next(vm => {
            vm.prevRoute = from;
        });
    },
    computed: {
        prevRoutePath() {return this.prevRoute ? this.prevRoute.path : '/'},
    }
}
</script>

我的解决方案是:

this.$router.options.history.state.back

最终代码:

export default defineComponent({
  name: 'Error404',
  data () {
    return {
      lastPath: null
    }
  },
  created () {
    this.lastPath = this.$router.options.history.state.back
  },
  computed: {
    prevRoutePatch () {
      return this.lastPath ? this.lastPath : '/dashboard'
    }
  }
})

此致。

对于适合我的 Vue 2.6:

In-App.vue 组件当你初始化 VueRouter 时你可以从和到细节如下:

export const globalState = Vue.observable({ from: {}, to: {} });
const router = new VueRouter({
    base: '/',
    routes: routes,
    mode: 'history',
    scrollBehavior(to, from, savedPosition) {
        Vue.set(globalState, 'from', from);
        Vue.set(globalState, 'to', to);
        return { x: 0, y: 0 };
    },
});

路线是您的路线,每次您导航到不同的 URL,您将拥有所有往返路线的详细信息。 然后你可以导入 globalState 对象并像那样使用它

     import { globalState } from './app';
     goBack() {
        const lastPath = globalState.from?.fullPath;
        const currentPath = globalState.to?.fullPath;
        if (lastPath && currentPath !== lastPath) 
           {
              this.$router.push(lastPath);
           } else {
              this.$router.push('another-path');
            }
        }