监听浏览器的后退按钮

首先在mounted()添加一个监听事件

if (window.history && window.history.pushState) {
      history.pushState(null, null, document.URL)
      window.addEventListener('popstate', this.back, false)
    }

接着编辑这个事件

  • 在本页面是否有在退出需要前完成的操作
  • 添加提示的信息,
  • 返回上一级的的路由信息
// 浏览器回退
    back() {
      this.$confirm(
        '检测到未保存的内容,是否在离开页面前保存修改?',
        '确认信息',
        {
          distinguishCancelAndClose: true,
          confirmButtonText: '保存',
          cancelButtonText: '放弃修改'
        }
      )
        .then(() => {
          // this.$router.go(-1)
          //保存文件
          this.saveDB()
          this.$router.push('/workbench')
        })
        .catch(action => {
          this.$message(
            {
              type: 'info',
              message:
                action === 'cancel' ? '放弃保存并离开页面' : '停留在当前页面'
            },
            this.$router.push('/workbench')
          )
        })
    },

最后别忘了销毁这个监听事件

第一种写到mounted()里面(这样写比较方便)

    this.$on('hook:beforeDestroy', () => {
      window.removeEventListener('popstate', this.back, false)
    })

第二种写到destroyed()里面

// 需要在退出页面的时候销毁这个监听事件
window.removeEventListener('popstate', this.back, false)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容