2017-04-08 57 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...'; 
    }, 
    } 
});