$emit 不会触发子事件 [英] $emit doesn't trigger child events
问题描述
对于 VueJS 2.0 项目,我在父组件上有以下内容
For a VueJS 2.0 project I have the following on the parent component
<template>
<child></child>
<button @click="$emit('childEvent)"></button>
</template>
在我拥有的子组件上:
{
events: { 'childEvent' : function(){.... },
ready() { this.$on('childEvent',...) },
methods: { childEvent() {....} }
}
按钮点击似乎没有任何效果.我是否需要创建一个父方法然后将其发送给孩子?我使用的是 vuejs 1.但现在我对父子通信的工作方式感到困惑
Nothing seems to work on button click. Is it that I need to create a parent method that would then emit to the child? I was using vuejs 1. but now I'm confused as to the ways parent to child communications work
推荐答案
虽然其他答案是正确的,但通常可以使用数据驱动的方法.
While the other answers are correct and it is usually possible to use a data driven approach.
我将添加这个给任何需要除道具以外的其他方法的人来寻找这个问题的答案.在尝试将焦点设置在自定义表单组件内的特定输入上时,我遇到了类似的问题.为此,我必须给自定义组件一个 ref 然后这样做.
I'm going to add this for anyone looking for an answer to this question who need a way other than props. I ran into a similar problem when trying to set focus on a particular input inside a custom form component. To do this I had to give the custom component a ref then do this.
this.$refs.customInput.$emit('focus');
//or
this.$refs.customInput.directlyCallMethod();
这会访问子组件的 vue 实例,然后您可以发出该组件听到的事件.
This access the vue instance of the child and then you can emit an event that is heard by that component.
这篇关于$emit 不会触发子事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!