PageLeave.vue 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <template>
  2. <div class="app-page">
  3. <h2>页面离开确认</h2>
  4. <p>你在 <strong class="text-strong">{{ pageTime }}</strong> 秒前打开本页面</p>
  5. <p>
  6. <strong class="text-strong">修改输入框的值</strong>后,页面在页签关闭/刷新/被替换时将会确认提示
  7. </p>
  8. <input
  9. v-model="editValue"
  10. type="text"
  11. >
  12. <p>
  13. <a
  14. class="demo-btn"
  15. @click="$routerTab.refresh()"
  16. >刷新</a>
  17. <a
  18. class="demo-btn"
  19. @click="$routerTab.close()"
  20. >关闭</a>
  21. <router-link
  22. class="demo-btn"
  23. :to="`?id=${+(this.$route.query.id || 0) + 1}`"
  24. >
  25. 替换
  26. </router-link>
  27. </p>
  28. </div>
  29. </template>
  30. <script>
  31. import pageTimer from '../mixins/pageTimer'
  32. export default {
  33. name: 'PageLeave',
  34. mixins: [pageTimer],
  35. data () {
  36. let value = '初始值'
  37. return {
  38. value,
  39. editValue: value
  40. }
  41. },
  42. // 页面离开前确认
  43. beforePageLeave (resolve, reject, tab, type) {
  44. // 离开类型
  45. const action = {
  46. close: '关闭',
  47. refresh: '刷新',
  48. replace: '替换'
  49. }[type]
  50. const msg = `您确认要${action}页签“${tab.title}”吗?`
  51. // 值未改变,则直接离开页签
  52. if (this.editValue === this.value) {
  53. resolve()
  54. return
  55. }
  56. // 值改变则确认提示
  57. if (confirm(msg)) {
  58. resolve()
  59. } else {
  60. reject('拒绝了页面离开')
  61. }
  62. /*
  63. // 此处使用了 Element 的 confirm 组件
  64. // 需将 closeOnHashChange 配置为 false,以避免路由切换导致确认框关闭
  65. this.$confirm(msg, '提示', { closeOnHashChange: false })
  66. .then(resolve)
  67. .catch(reject)
  68. */
  69. }
  70. }
  71. </script>