Vue.js - Calling a component's method from Vue instance

浪子不回头ぞ 提交于 2019-12-08 10:42:47

问题


I have a created a Vue instance and a global component. How can I call the component's method from my Vue instance?

In my Vue instance I did this:

methods: {
    handleTabClick: function(tab, event) {
        if (tab.name == 'log') {
            call loadLog function in log component
        }
    }
}

Then my component is defined as this:

Vue.component('jettLog', {
    props: ['shop'],

    data() {
        return {
            log: [],
            logLoading : true
        }
    },

    methods: {
        loadLog: function() {
            console.log("Load");
        },
    },
});

How can I call jettLog's function loadLog from handleTabClick()?

I see different explanations and now I am wondering what's the best way to do it?

Thanks!


回答1:


Register a global event bus whixh is an empty vue instance like this:

Var EventBus = new Vue();

in your vue instance emit an event with EventVus.$emit()

methods: {
    handleTabClick: function(tab, event) {
        if (tab.name == 'log') {
            EventBus.$emit('log-event')
        }
    }
}

$emit() takes two arguments: 1: event name 2. event data (optional)

In the created hook of jettLog component set up an event listener on the EventBus and perform your logic when a paticular event is emitted

Vue.component('jettLog', {
    props: ['shop'],

    data() {
        return {
            log: [],
            logLoading : true
        }
    },
    created(){
        var self = this;
        EventBus.$on('log-event', function(eventData){
            self.loadLog();
        });
    },
    methods: {
        loadLog: function() {
            console.log("Load");
        },
    },
}); 

Check this out for more info



来源:https://stackoverflow.com/questions/47494833/vue-js-calling-a-components-method-from-vue-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!