mixins.tsvue
1 import { Vue, Component, Watch } from "vue-property-decorator" 2 Component.registerHooks([ 3 'beforeRouteLeave' 4 ]) 5 @Component 6 /* 此mixin用來頁面離開時編輯提示, 7 若是組件引入該mixin,那麼默認:url改變或者刷新關閉時會給出提示; 8 若是引入的組件更改url時不須要提示(好比點擊保存按鈕時),那麼須要將showLeaveHint手動置爲false */ 9 export class LeaveHintMixin extends Vue { 10 showLeaveHint: boolean = true; 11 hintMessage: string = '頁面中有正在編輯的內容,繼續將不會保存'; 12 13 /* ---- 函數 ---- */ 14 showLeaveHintFun(next) { 15 if (window.confirm(this.hintMessage)) { 16 next(); 17 } else { 18 next(false); 19 } 20 } 21 22 /* 綁定與解綁瀏覽器刷新關閉事件 */ 23 bindBeforeunload() { 24 // 點擊刷新、關閉按鈕,直接經過瀏覽器給出提示 25 window.onbeforeunload = (event) => { 26 event.returnValue = this.hintMessage; 27 return this.hintMessage; 28 }; 29 } 30 unbindBeforeunload() { 31 window.onbeforeunload = null; 32 } 33 34 /* ---- 生命週期 ---- */ 35 // 改變url時,給出提示 36 beforeRouteLeave(to, from, next) { 37 if (this.showLeaveHint) { 38 this.showLeaveHintFun(next); 39 } else { 40 next(); 41 } 42 } 43 // 組件渲染完綁定瀏覽器刷新關閉事件 44 mounted() { 45 if (this.showLeaveHint) { 46 this.bindBeforeunload(); 47 } 48 } 49 // 組件摧毀時解綁事件 50 beforeDestroy() { 51 this.unbindBeforeunload(); 52 } 53 54 // 添加監控使得組件可以更加靈活控制編輯提示,組件改變showLeaveHint時,即可以綁定或者解綁事件控制提示 55 @Watch('showLeaveHint') 56 bindClick(val) { 57 if (val) { 58 this.bindBeforeunload(); 59 } else { 60 this.unbindBeforeunload(); 61 } 62 } 63 }
使用方法 use.ts瀏覽器
1 import { Vue, Watch, Component } from 'vue-property-decorator' 2 import { mixins } from 'vue-class-component' 3 import { LeaveHintMixin } from '../../common/mixins' 4 5 @Component 6 7 export default class Use extends mixins(LeaveHintMixin) { 8 //引入mixins.ts默認更改url、刷新、關閉時會給出提示 9 10 showLeaveHint = false; // 這樣會覆蓋mixins.ts中的showLeaveHint,會改成默認沒提示,跟不引入同樣 11 12 //後面經過改變this.showLeaveHint 能夠控制更改url、刷新、關閉時是否給出提示 13 }