Vue中fancybox回调调用组件方法报this.messageAlert is not a function如何解决
错误根因
你遇到的this.messageAlert is not a function报错是this指向绑定错误导致的:afterClose回调里你用了普通匿名函数,普通函数的this会绑定到它的调用方上下文,这里的this指向的是fancybox的实例对象,而不是当前Vue组件实例,所以找不到挂载在Vue组件实例上的messageAlert方法。
修复方案
以下三个方案选其一即可,优先推荐方案1:
方案1:用箭头函数替换普通回调(最简单)
箭头函数不会创建自己的this,会继承外层作用域的this指向,直接拿到Vue组件实例:
<template> <div> <v-btn @click="openCal">Open Now</v-btn> </div> </template> <script> export default { methods: { messageAlert() { alert("Method is called") }, openCal() { let src = 'https://google.com/' $.fancybox.open({ type : 'iframe', scrolling : 'yes', src : src, opts : { // 如果afterShow里也要调用组件方法也改成箭头函数即可 afterShow : (instance, current) => { $("body").attr("style", "overflow: hidden; position: fixed;") // setTimeout(function() { $(".fancybox-content").attr("style", "height: 90% !important; overflow: scroll;") $(".fancybox-content > iframe").attr("style", "height: 101% !important; overflow: scroll;") $(".fancybox-content > iframe").attr("scrolling", "yes") // }, 500) }, // 改成箭头函数 afterClose : (instance, current) => { $("body").attr("style", "") this.messageAlert(); } } }); } } }; </script>
方案2:提前保存Vue实例指向
在回调外层先把组件实例存为变量,回调里直接用变量调用方法,兼容性最好:
openCal() { // 提前保存组件实例 const vm = this; let src = 'https://google.com/' $.fancybox.open({ // 其他配置不变 opts : { afterClose : function( instance, current ) { $("body").attr("style", "") // 用提前保存的实例调用方法 vm.messageAlert(); } } }); }
方案3:用bind手动绑定this指向
给回调函数绑定外层的this,强制让回调里的this指向Vue组件实例:
afterClose : function( instance, current ) { $("body").attr("style", "") this.messageAlert(); // 手动绑定this }.bind(this)
内容的提问来源于stack exchange,提问作者user12763413
相关产品推荐
相关产品推荐

