首页 > 其他分享 >VueJS使用addEventListener的事件如何触发执行函数的this

VueJS使用addEventListener的事件如何触发执行函数的this

时间:2022-12-29 11:35:58浏览次数:55  
标签:触发 函数 VueJS max alert 答卷 addEventListener document

1、使用浏览器监听切屏为例

此处为考虑浏览器兼容性推荐使用:document.addEventListener

1.1、正常函数使用如下:

let n = 0;
let max = 3; //   切屏最大次数
document.addEventListener("visibilitychange", function () {
    if(document.visibilityState == 'hidden'){
        n++;
    } else if(document.visibilityState == 'visible') {
        if (n > max) {
            this.$alert('你已经切换离开考试页面超过'+max+"次系统将自动提交答卷!", '警告', {
                confirmButtonText: '知道了',
                callback: action => {
                    this.msgSuccess("系统自动提交答卷!");
                }
            });
            return;
        }
        this.$alert('你已经切换离开考试页面'+n+'次,如果超过'+max+"次系统会自动提交答卷,请认真作答!", '警告', {
            confirmButtonText: '知道了',
            callback: action => {}
        });
    }
});

 this.$alert()为vue的MessageBox弹框组件

运行后报:提示this.$alert()不是一个函数

此时我们尝试在document函数里面打印this到控制台看看

console.log("this===",this);

控制台输出信息:指向的是调用addEventListener的对象

我们使用document对象去调用VueJS的组件函数肯定是行不通的,那么怎样可以拿到VueJS的this呢?我们只需稍作修改

1.2、bind()绑定事件指定函数

修改后的代码如下:

 

let n = 0;
let max = 3; //   切屏最大次数
let fn = function () {
    console.log("this===",this);
    if(document.visibilityState == 'hidden'){
        n++;
    } else if(document.visibilityState == 'visible') {
        if (n > max) {
            this.$alert('你已经切换离开考试页面超过'+max+"次系统将自动提交答卷!", '警告', {
                confirmButtonText: '知道了',
                callback: action => {
                    this.msgSuccess("系统自动提交答卷!");
                }
            });
            return;
        }
        this.$alert('你已经切换离开考试页面'+n+'次,如果超过'+max+"次系统会自动提交答卷,请认真作答!", '警告', {
            confirmButtonText: '知道了',
            callback: action => {}
        });
    }
}
// 使用bind绑定的事件才是指向函数,否则指向的是调用addEventListener的对象
document.addEventListener("visibilitychange", fn.bind(this));

 详解:

  1. 将触发事件后执行的函数抽到外部,作为外部函数并赋予函数名
  2. 在事件中使用函数名.bind('指定函数');即可在执行的函数中获取到bind绑定的指定函数

控制台查看此时的this为

效果图:

参考博文:https://www.jb51.net/article/253509.htm

标签:触发,函数,VueJS,max,alert,答卷,addEventListener,document
From: https://www.cnblogs.com/aerfazhe/p/17012043.html

相关文章