简体   繁体   中英

How do perform state changes in my Vue.js page when navigating back through browser history after using `pushState`?

I'm writing a fairly simple search page with Vue (my first real Vue project) and I have the following situation set up:

  1. When a query is passed in via the URL, I parse the value out of the URL, populate the search box in the page and perform the search. This works ✅
  2. When the user edits text the search box, after a brief debounce pause I do the search via an API call, present the results, construct a new URL from the current page URL + the search query as a query parameter and push it into the browser history using window.history.pushState . This works ✅
  3. When the user presses the back button, the URL in the browser address bar changes back to the previous history entry (and therefore the previous search query), but the page does not update any of it's content and none of The Vue methods like created or mounted are called. I understand that this is probably intentional because the whole point of this API is to avoid a page reload, but I'd like to update the state of my page so that the search box and results match the URL in the address bar. I can't find a way to do that.

I am not using The Vue Router as I don't think I need it. This is a single page site with just this search on it.

Thanks!

Thanks to Slim in the comment above, the solution to this was indeed to listen to the popstate event. I ended up with code something like this inside my created function:

var vm = this
window.addEventListener("popstate", function(event) {
  if (event.state) {
    vm.query = event.state.query
  } else {
    vm.query = ""
  }
});

This of course assumes that I was passing the query in the state when calling pushState , which I already was!

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