【问题标题】:How to call methods in App.vue from the vue components如何从 vue 组件调用 App.vue 中的方法
【发布时间】:2017-09-03 16:55:39
【问题描述】:

我有一个 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中的方法?

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    你可以像这样执行根实例方法: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");
            }
        }
    })
    

    【讨论】:

    • 这是一种代码异味,还是一种常见的做事方式?
    • 非常感谢,我很久以前就在找这个了
    【解决方案2】:

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

    检查this简单的小提琴作为一个愿景

    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...';
            },
        }
    });
    

    【讨论】:

    • 如果您想让您的组件与应用程序分离,这是正确的做法。简而言之,如果您想拥有可重用的组件,您需要遵循@YaserKH 示例。我会推荐这个作为基于架构最佳实践的正确答案。
    • 聚会有点晚了,但这是要走的路。我猜你也可以将路由用于更复杂的应用程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2021-09-28
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 2018-02-19
    相关资源
    最近更新 更多