繁体   English   中英

如何使用后退按钮检查用户是否到达路线或 url?

[英]How to check that user came to the route or url using back button?

我需要做一些功能,特别是当用户回到已经访问过的页面(历史)时。如何做到这一点?

Considering your router is not configured in history mode because from vue router docs "history mode, which leverages the history.pushState API to achieve URL navigation without a page reload", You can hook into vue router event to save the previous url

router.beforeEach(async (to, from, next) => {
    previousRoutes.push(from)
    next()
})

更多信息在这里https://router.vuejs.org/guide/advanced/navigation-guards.html现在您可以检查,如果用户回来了,如果路由已经存在于 previousRoutes - 到一个已经访问过的页面。

我认为您无法确定用户按下了back按钮。

但是您可以保留访问过的路线列表并检查用户是否去过该路线。

您可以使用vuex来存储访问过的路由,方法是添加一个突变以将新路由推送到它。

var store = new Vuex.Store({
  state: {
    visitedRoutes: [
    ]
  },
  mutations: {
     ADD_VISITED_PAGE (state, route) {
      // mutate state
      state.visitedRoutes.push(route)
    }
  }
})

并添加一个全局后挂钩来触发你的突变

router.afterEach( (to, from) => {
  store.commit('ADD_VISITED_PAGE', from)
})

之后,如果用户访问过该页面,您可以签入您的组件。

mounted () {
 if (this.$store.state.visitedRoutes.contains(this.$route.name)) {
   // you've been here before
 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM