Home >Web Front-end >Front-end Q&A >vue router delete history
In the process of developing single-page applications using Vue Router, we often need to allow users to clear the browser history. But Vue Router does not provide a built-in method to help us implement this function, so we need to find a way to implement it ourselves.
Method 1:
One method is to use a method called "replaceState" in Javascript, which can replace the current browser history entry with a new entry, thereby achieving Purpose of deleting history. We can use this method with Vue Router. The specific steps are as follows:
router.beforeEach((to, from, next) => { sessionStorage.setItem('toPath', to.fullPath) // 保存即将跳转的路由对象的路径 next() })
function clearHistory() { const toPath = sessionStorage.getItem('toPath') history.replaceState(null, '', toPath) sessionStorage.removeItem('toPath') }
export default { clearHistory }
To summarize the steps of this method:
Method 2:
Another way to clear browser history is to use the hook function of Vue Router. The specific steps are as follows:
router.afterEach((to, from) => { if (!sessionStorage.getItem('isBack')) { history.replaceState(null, '', from.fullPath) sessionStorage.setItem('fromPath', from.fullPath) // 保存从哪个路由页面来 } sessionStorage.removeItem('isBack') // 操作完后,清除标识变量 })
this.$emit('clearHistory')
<template> <button @click="handleClearHistory">清除历史记录</button> </template> <script> export default { methods: { handleClearHistory() { this.$router.replace(sessionStorage.getItem('fromPath')) sessionStorage.setItem('isBack', 'true') } } } </script>
Summarize the steps of this method:
To sum up, we can use either of these two methods to achieve the function of deleting browser history. Which method to choose can be based on specific business needs and development scene to determine. Hope this article is helpful to you.
The above is the detailed content of vue router delete history. For more information, please follow other related articles on the PHP Chinese website!