如何从 vue 组件调用 App.vue 中的方法

How to call methods in App.vue from the vue components

我有一个 vue 组件和一个 vue 元素声明,如下所示

Vue.component('todo-item', {
    template: '<li>This is a todo</li>'
    methods: {
        test: function() {
            
            // I am getting an error here
            app.aNewFunction();
        }
    }
})

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!'
    },
    methods: {
        aNewFunction: function() {
            alert("inside");
        }
    }
}) 

如何从vue组件调用vue app中的方法?

您可以像这样执行根实例方法:this.$root.methodName()

Vue.component('todo-item', {
    template: '<li>This is a todo</li>',
    methods: {
        test: function() {
            this.$root.aNewFunction();
        }
    },
    mounted() {
        this.test();
    }
})
  
new Vue({
    el: '#app',
    template: '<todo-item></todo-item>',
    methods: {
        aNewFunction: function() {
            alert("inside");
        }
    }
})

另一种我认为更符合Vuejs架构的解决方案,是在子组件和它的父组件之间使用事件监听器和发射器进行通信。

检查this简单fiddle作为愿景

Vue.component('todo-item', {
    template: '<li>This is a todo</li>',
    methods: {
        test: function() {
            console.log('Emmit this Event.');
            this.$emit('yourevent');
        }
    },
    created() {
        this.test();
    }
});

new Vue({
    el: '#vue-app',
    data: {
        'message': '',
    },
    methods: {
        aNewFunction(event) {
            console.log('yourevent Is Triggered!');
            this.message = 'Do Stuff...';
        },
    }
});