javascript - 从匿名函数访问 Vue 方法

标签 javascript vue.js

我只是玩玩 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/

相关文章:

javascript - 如何注册 Vue 组件?

javascript - 如何在 ASP.NET 的 TextBox 输入中添加连字符?

javascript - AngularJS:位置更改后刷新 View

javascript - 调度和监听不同组件中的事件 - reactjs

javascript - SQLite 数据库插入时难以转义单引号字符

vue.js - Vuejs v-for 循环与标签组合

javascript - 关于表示持续时间的 HTML 表单输入的建议(使用 Javascript/JQuery)

vue.js - vuejs属性中的语法 `${k}`是什么?

vue.js - Vue 事件处理程序的可组合函数

vue.js - 在 Vue.js 中如何使导航在向下滚动事件中淡入淡出并在滚动 pageYOffset = 0 处淡出