美文网首页
监听浏览器的后退按钮

监听浏览器的后退按钮

作者: 落墨诗卷 | 来源:发表于2021-11-22 22:24 被阅读0次

首先在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)

相关文章

网友评论

      本文标题:监听浏览器的后退按钮

      本文链接:https://www.haomeiwen.com/subject/kvrbtrtx.html