Last visit page tracking with vuex

34 Views Asked by At

I have a vue application and I want somehow save or memorize the last visited page with vuex-persistentstate. What I want is: I have 3 pages for example A,B,C and all three leads to Page D and on Page D there is a "cancel/finish" button. Clicking it now, redirect to Home Page. But I want to return to the last visit page depending where I was (A,B or C).

I want to realize it with vuex-persistentstate

So far I have this.

src/store/index.js

export default createStore({
  plugins: [
    createPersistedState({
      key: 'xx',
      paths: [
        'global.pageAfterFinishClick',
        ...,
      ],
    }),
  ],

And here src/store/global/index.js

state: {
    pageAfterFinishClick: '/'
...
}

I think next step is to add mutation and action and update my router?

mutations: {
  // Other mutations...
  [SET_PAGE_AFTER_FINISH_CLICK](state, payload) {
    state.pageAfterFinishClick = payload;
  },
}

and

actions: {
  // Other actions...
  setPageAfterFinishClick({ commit }, page) {
    commit(SET_PAGE_AFTER_FINISH_CLICK, page);
  },
}

I'm struggling with this step and need your help.

1

There are 1 best solutions below

0
Mohesn Mahmoudi On

This is the way I do it:

Vuex store

const store = new Vuex.Store({
  state: {
    previousRoute: null,
  },
  mutations: {
    setPreviousRoute(state, route) {
      state.previousRoute = route;
    },
  },
  actions: {
    updatePreviousRoute({ commit }, route) {
      commit('setPreviousRoute', route);
    },
  },
});

And then I Update router setup to dispatch the updatePreviousRoute action whenever a route navigation occurs:

const router = new VueRouter({
  mode: 'history',
  routes,
});

router.beforeEach((to, from, next) => {
  // Dispatch action to update previous route
  store.dispatch('updatePreviousRoute', from);
  next();
});

With this setup, every time a route navigation occurs, the updatePreviousRoute action is dispatched with the previous route information, and it updates the Vuex store with the previous route.

And then I use the previousRoute property from the Vuex store to navigate back:

methods: {
  onCancelFinishClick() {
    // Navigate to the previous page
    this.$router.push(this.$store.state.previousRoute || '/');
  },
},

This will navigate to the previous page if available, or to the home page ('/') if there is no previous route stored.