简体   繁体   中英

How to check if the user is going to the previous page with vue-router?

Context

I have this LightGallery plugin, and I noticed that when it is in fullscreen, clicking on the previous page button will not close the LightGallery but go "silently" to the previous page without the user to be aware of it.

In my case, I am building an SPA using VueJS and VueRouter, and when the user closes the LightGallery after clicking the previous page, it is confusing because the user expected to get back where he/she was.

I know that VueRouter has navigation guards, but I miss one feature, to easily know if the user is going back or not.

I am using VueRouter in "history" mode.

As I use the "history" mode, I guess this explains why the lg-hash plugin for LightGallery is of no help. It only appens a hash to my route, but the VueRouter is working independently of this hash.

Question

How to know if the user is going to the previous page using VueRouter?

In "history" mode, VueRouter is using the History API. Is there anyway to use it to have a clue? Or should I eventually store manually the history and process it at each route change?

I have found that we can listen to previous/next page using window.onpopstate = function() {} , but can I exclusively check for the previous page only using this method?

In my router instantation I have:

const router = new Router({
 mode: "history",
 scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      to.meta.fromHistory = true;
      return savedPosition;
    } else {
      return { x: 0, y: 0 };
    }
  },
 // (...)

However, as you mentioned, there's no clear way to catch whether that's a back or a forward navigation taking place.

As per the official documentation :

The scrollBehavior function receives the to and from route objects. The third argument, savedPosition , is only available if this is a popstate navigation (triggered by the browser's back/forward buttons).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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