zoukankan      html  css  js  c++  java
  • 使用vue的mixins混入实现对正在编辑的页面离开时提示

    mixins.ts

     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 }
    View Code

    使用方法 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 }
    View Code
  • 相关阅读:
    课堂讨论及思考
    问题账户需求分析
    阅读计划
    我们应当怎样做需求分析
    常用JavaScript触发事件
    form表单的字符串进行utf-8编码
    关于编码
    JavaScript弹窗
    测试
    感谢博客园
  • 原文地址:https://www.cnblogs.com/XHappyness/p/9935504.html
Copyright © 2011-2022 走看看