微信小程序Component组件调用回调函数this指向不是本页面
在微信小程序中如果在Component中写回调函数, 那么this的指向是undefined
Component({ /** * 组件的属性列表 */ properties: { }, /** * 组件的初始数据 */ data: { }, /** * 组件的方法列表 */ methods: { getData(callback) { if (callback) { callback(); } }, funcA () { console.log(this) //这里的this不是指向Component实例 }, }, lifetimes: { attached: function() { this.getData(this.funcA) }, }, });
解决办法: 在调用回调函数的时候使用箭头函数
Component({ /** * 组件的属性列表 */ properties: { }, /** * 组件的初始数据 */ data: { }, /** * 组件的方法列表 */ methods: { getData(callback) { if (callback) { callback(); } }, funcA () { console.log(this) //这里的this不是指向Component实例 }, }, lifetimes: { attached: function() { this.getData(()=> this.funcA()) }, }, });
- 上一篇 »检测并更新下载最新版微信小程序
- 下一篇 »taro 微信小程序原生作用域获取