Vue.js survey using browser back/forward buttons Vue.js survey using browser back/forward buttons vue.js vue.js

Vue.js survey using browser back/forward buttons


You could use the vue-router as you implied. The simplest solution for your example, though, is to just use the browser's history API. Steps:

  • When moving to previous/next questions, use history.pushState to add a state to the browser's history:

     methods: {     next: function() {         this.questionIndex++;         this.updateHistory();  // added this line     },     prev: function() {         this.questionIndex--;         this.updateHistory();  // added this line     },     updateHistory: function() {  // added this method         history.pushState({questionIndex: this.questionIndex}, "Question " + this.questionIndex);     } }
  • And now all you have to do is listen to those history state changes. A good spot to hook a listener to this event is the mounted:

     mounted: function() {     var vm = this;     window.addEventListener('popstate', function(event) {         vm.questionIndex = (event.state || {questionIndex: 0}).questionIndex;     }); },

And that's it.

Click here for the a demo page at JSBin (check the history button).

You'll find the source for that demo here.