从组件内部创建的 FullCalendar 对象访问 Vue 组件对象

Accessing Vue component object from inside FullCalendar object created inside the component

我在 VueJS 中使用完整日历,每当我在日历上单击某个时间时,我想打开一个自定义模式。但是,我需要在 Full calendar 对象之外调用一个单独的函数来打开我的模式,我不确定如何解决这个问题,因为在 Full Calendar 中使用 this 将引用该对象和 Vue 组件对象.我需要以某种方式获取 Vue 组件对象,这是我迄今为止尝试过但无济于事的方法

export default {
    name: 'MyComponent',
    methods: {
        myFunc () {
            // should get called from inside fullCalendar below
            this.$store.dispatch()  // this.$store works here since `this` refers to Vue component 
        }
    },
    mounted () {

        $('#calendar').fullCalendar({
        header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay,listWeek'
        },
        navLinks: true,
        eventLimit: true,
        defaultView: 'agendaWeek',
        editable: true,
        selectable: true,
        selectHelper: true,
        select: function (start, end) {
            console.log(this)   // refers to Full Calendar object
            console.log(this.$parent)   // getting null, need to call function in vue component
            console.log(this.myFunc()) // cannot do this since this will try to call a function in Full Calendar library
            console.log(this.$parent.$store) // getting null, need to get store that I defined 
        }
    }
}

这是新用户遇到的常见 javascript 范围界定问题。正如您所发现的,this 是一个流动的概念。

有两种解决方法。第一种是使用箭头函数。箭头函数将 this 绑定到创建它们的上下文:

select:  (start, end) => {
        console.log(this)   // should be your vue instance 
    }

另一个是在 mounted 函数的顶部存储对 this 的引用。此变量通常命名为 self

var self = this;

....

select: function (start, end) {
        console.log(self) // also your vue instance
    }

这样,即使 this 在回调中重新绑定到不同的对象,您仍然可以通过 self 变量获取原始对象上下文。

此技术在很大程度上已被箭头函数淘汰,但仍可用于支持旧版浏览器,值得了解。