Reputation: 33
I need to do some functionality especially when the user come back to already visited page(history).How to do this?
Upvotes: 1
Views: 1232
Reputation: 14171
I don't think you can know for sure that a user pushed the back
button.
But you can keep a list of visited routes and check if the user has been to that route.
You can use vuex to store the visited routes, by adding a mutation to push new routes to it.
var store = new Vuex.Store({
state: {
visitedRoutes: [
]
},
mutations: {
ADD_VISITED_PAGE (state, route) {
// mutate state
state.visitedRoutes.push(route)
}
}
})
And add a global after hook to trigger your mutation
router.afterEach( (to, from) => {
store.commit('ADD_VISITED_PAGE', from)
})
After that you can check in your components if a user has visited that page or not.
mounted () {
if (this.$store.state.visitedRoutes.contains(this.$route.name)) {
// you've been here before
}
}
Upvotes: 1
Reputation: 496
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()
})
More information here https://router.vuejs.org/guide/advanced/navigation-guards.html Now you can check to see, if the user came back, if the route is already present in previousRoutes - to an already visited page.
Upvotes: 0