我只是玩玩 Vue.js(对 javascript 也很陌生)并尝试访问我的 Google 日历中的事件。
在控制台中查看时,我总是得到“未定义”。
new Vue({
el: '#app',
data: {
client_id: 'my_client_id',
scopes: ["https://www.googleapis.com/auth/calendar.readonly"],
events: {
title: 'Upcoming Events',
items: [],
}
},
created: function () {
this.loadCalendarApi();
},
methods: {
addEvent: function (event) {
this.events.items.push({
title: event.summary,
date: event.start.dateTime
});
},
loadCalendarApi: function () {
gapi.client.load('calendar', 'v3', this.listUpcomingEvents);
},
listUpcomingEvents: function () {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
});
var events = this.requestEvents(request);
console.log(events);
},
requestEvents: function (request) {
return request.execute(function (resp) {
resp.items;
});
},
},
});
我认为有问题的代码在 requestEvents 方法中的某处。
我也知道“this.addEvent”不在能够从 request.execute 函数内部引用 Vue 对象的范围内,但我不知道我需要更改什么。
任何人都可以帮助我或让我知道我做错了什么吗?
谢谢!
最佳答案
有两种方法,一种是将 execute(function)
更改为 execute(function, vue)
并传递 this
作为第二个参数。然后你可以像这样访问它:
//update your execute function to pass along the vue variable into the response, then
requestEvents: function (request) {
var events = request.execute(function (resp, vue) {
for (i = 0; i < resp.items.length; i++) {
vue.addEvent(resp.items[i]);
}
}, this);
return events;
}
或者如果您有可用的 jQuery,您可以查看 $.proxy()
,它改变了一个函数以使用当前上下文:https://api.jquery.com/jQuery.proxy/
requestEvents: function (request) {
var events = request.execute($.proxy(function (resp) {
for (i = 0; i < resp.items.length; i++) {
this.addEvent(resp.items[i]);
}
}, this));
return events;
}
这样匿名响应函数将在 Vue 对象的上下文中运行。
编辑:我也找到了这个页面,它展示了如何使用原生 JS、jQuery 或 Underscore 将当前上下文绑定(bind)到一个函数。这些中的任何一个都可以工作:https://jsperf.com/bind-vs-jquery-proxy/5
关于javascript - 从匿名函数访问 Vue 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34729569/