Vue3项目中禁止浏览器回退或前进功能

19 篇文章 0 订阅
4 篇文章 0 订阅
在Vue3项目中,可以通过监听popstate事件并使用history.pushState来禁止浏览器的回退和前进功能。这可以在组件的onMounted钩子中实现,或者在全局级别如main.js/main.ts中设置。另外,还可以利用VueRouter的afterEach守卫或修改scrollBehavior来达到相同效果。
摘要由CSDN通过智能技术生成

Vue3项目中禁止浏览器回退或前进功能

页面加载时就进行禁止

<template>
</template>

<script lang="ts">
import { defineComponent, onMounted } from 'vue';

export default defineComponent({
  name: '',
  setup() {
    // 在要禁止后退的页面进行添加
    onMounted(() => {
      history.pushState(null, null, document.URL);
      
      window.addEventListener(
        'popstate',
        function(e) {
          history.pushState(null, null, document.URL);
        },false);
    });

    return { t };
  },
});
</script>
<style lang="scss">
</style>

总结:若是需要全局禁用则可在
1、main.js/main.ts中设置监听:
window.addEventListener(‘popstate’, function() {
history.pushState(null, null, document.URL)
})
2、在router的index.js中:
const router = new Router({
mode: ‘hash’,
routes,
scrollBehavior: () => {
history.pushState(null, null, document.URL)
}
})
或者使用路由守卫:
router.afterEach((to, from) => {
history.pushState(null, null, location.protocol + ‘//’ + location.host + ‘/#’ + to.path)
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值