从 VueJS 中的事件传递数据

Pass data from event in VueJS

所以,我正在使用 VueJS 开发一个 Cordova Android 应用程序,我使用 background geolocation plugin

它发出名为 'location' 的全局事件,我的应用程序在 main.js

中侦听该事件
function onDeviceReady () {
  BackgroundGeolocation.on('location', (location) => {})
}

document.addEventListener('deviceready', onDeviceReady, false)

每次触发事件时如何将位置数据传递给组件中的变量?

尝试在组件的 mounted 方法中添加事件侦听器,并将其处理程序指向组件方法,如下所示:

export default {
    data() {
        return {
            location: null,
        }
    },
    mounted() {
        document.addEventListener('deviceready', this.onDeviceReady, false)
    },
    beforeDestroy() {
        // remember to remove event listener
        document.removeEventListener('deviceready', this.onDeviceReady)
    },
    methods: {
        onDeviceReady() {
            BackgroundGeolocation.on('location', this.handleLocation)
        },
        handleLocation(location) {
            // you've got location!
            this.location = location
        }
    }
})