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

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)
})

猜你喜欢

转载自blog.csdn.net/m0_50298323/article/details/131184080