一.禁用前进后退功能一.禁用前进后退功能在开发vue应用中,如何禁用浏览器的前进后退功能呢?网上搜到的答案基本如下:
history.pushState(null, null, document.URL)
window.addEventListener('popstate', function() {
history.pushState(null, null, document.URL)
})
history.pushState(null, null, document.URL)
window.addEventListener('popstate', function() {
history.pushState(null, null, document.URL)
})但应该放在哪儿?但应该放在哪儿?经过尝试,我是如此写的:main.js中,增加popstate监听
window.addEventListener('popstate', function() {
history.pushState(null, null, document.URL)
})
window.addEventListener('popstate', function() {
history.pushState(null, null, document.URL)
})router的index.js中:
const router = new Router({
mode: 'hash',
routes,
scrollBehavior: () => {

history.pushState(null, null, document.URL)
}
})
const router = new Router({
mode: 'hash',
routes,
scrollBehavior: () => {

history.pushState(null, null, document.URL)
}
})这里我将pushState放在了scrollBehavior中。当然,你也可以尝试放在router的beforeEach/afterEach中
router.afterEach((to, from) => {
history.pushState(null, null, location.protocol + '//' + location.host + '/#' + to.path)
})
router.afterEach((to, from) => {
history.pushState(null, null, location.protocol + '//' + location.host + '/#' + to.path)
})不过这里的URL就不能使用document.URL了,因为此时的 document.URL 指向的是上一页面的 URL,这会导致第一次页面回退禁用无效。二、history二、historyhistory 对象包含浏览器历史。常见属性/方法:常见属性/方法:history.length - 属性保存着历史记录的URL数量;history.back() - 等同于在浏览器点击后退按钮;history.forward() - 等同于在浏览器中点击前进按钮;history.go() - 加载 history 列表中的某个具体页面。H5新增了属性/方法/事件:H5新增了属性/方法/事件:history.state - 属性用来保存记录对象;history.pushState() - 向浏览器的历史记录中添加一个状态;history.replaceState() - 修改当前历史记录实体;popstate事件 - 当活动历史记录条目更改时,将触发
1.history.state
1.history.state返回当前页面的state对象
2.history.pushState(state, title, url)
2.history.pushState(state, title, url)state: 状态对象可以是任何可以序列化的对象。title: 当前大多数浏览器都忽略此参数,尽管将来可能会使用它。url: 新历史记录条目的URL由此参数指定。如果未指定此参数,则将其设置为文档的当前URL。
3.history.replaceState(state, title, url)
3.history.replaceState(state, title, url)修改当前历史记录实体,如果你想更新当前的state对象或者当前历史实体的URL来响应用户的的动作的话这个方法将会非常有用。参数与pushState类似。
4.popstate事件
4.popstate事件当活动历史记录条目更改时,将触发popstate事件。需要注意的是调用history.pushState()或history.replaceState()不会触发popstate事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back()或者history.forward()方法)。不同的浏览器在加载页面时处理popstate事件的形式存在差异。页面加载时Chrome和Safari通常会触发(emit )popstate事件,但Firefox则不会。补充知识:vue实现前进刷新,后退不刷新心得补充知识:补充知识:vue实现前进刷新,后退不刷新心得最近在用vue做移动端的项目。希望实现前进刷新、后退不刷新的效果。即加载过的界面能缓存起来(返回不用重新加载),关闭的界面能被销毁掉(再进入时重新加载)。例如对a->b 前进(b)刷新,b->a 后退(a)不刷新。需求:需求:默认显示 AB 跳到 A,A 不刷新C 跳到 A,A 刷新实现方式:在 A 路由里面设置 meta 属性在 B 组件里面设置 beforeRouteLeave:vue新手注意:在App.vue中配置缓存的视图组件在 C 组件里面设置 beforeRouteLeave:以上这篇Vue 禁用浏览器的前进后退操作就是小编分享给大家的全部内容了,希望能给大家一个参考。