2017-04-08 53 views
1

调用VUE应用程序的方法我有一个VUE组件和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应用程序的方法?

回答

2

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

确定。谢谢。它运行良好。 –

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