Vue.js - 从 Vue 实例调用组件的方法 [英] Vue.js - Calling a component's method from Vue instance

查看:92
本文介绍了Vue.js - 从 Vue 实例调用组件的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 Vue 实例和一个全局组件.如何从我的 Vue 实例调用组件的方法?

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

在我的 Vue 实例中,我这样做了:

In my Vue instance I did this:

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

然后我的组件定义如下:

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

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

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

如何从handleTabClick()调用jettLog的函数loadLog?

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?

谢谢!

推荐答案

注册一个全局事件总线 whixh 是一个空的 vue 实例,如下所示:

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

Var EventBus = new Vue();

在你的 vue 实例中用 EventVus.$emit()

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

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

$emit() 有两个参数:1:事件名称2. 事件数据(可选)

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

jettLog 组件的创建钩子中,在 EventBus 上设置一个事件监听器,并在发出特定事件时执行您的逻辑

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

查看此了解更多信息

这篇关于Vue.js - 从 Vue 实例调用组件的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆