【问题标题】:Vue.js $emit event from parent and receive it on a component (child)Vue.js $emit 来自父级的事件并在组件(子级)上接收它
【发布时间】:2019-04-05 14:55:37
【问题描述】:

我似乎无法让它工作!

我已将$emit 代码添加到我的点击事件中以发出自定义事件。

<h2 class="form_section--header">Business Hours - <a href="javascript:void(0)" v-on:click="$emit('addBusinessHours', null)">Add New</a></h2>

然后我在同一个 Vue 应用程序中的组件上监听此事件,我在模板上执行此操作,我更愿意在代码中执行此操作:

<business-hours :injected-data="hours" :injected-days="data.days[0]" v-on:addBusinessHours="test()">

不确定这是否会影响它,但我的 business-hours 组件在另一个组件中。

【问题讨论】:

  • 通常你不应该使用事件来传递一些东西给子组件。但是如果你必须这样做,你可以使用 $refs 直接访问孩子,也可以使用 this.$root.$emit 和 this.$root.$on

标签: javascript vue.js


【解决方案1】:

我建议您使用单独的类来从组件发出事件。

首先创建你的 Event 类,例如,我调用 EventBus。

/* Events.js */
import Vue from 'vue';
export const EventBus = new Vue();

然后您导入到您希望从以下位置发出值的组件:

import {EventBus} from '@/events.js'

然后你发送事件

<h2 class="form_section--header">Business Hours - <a href="javascript:void(0)" v-on:click="emitEvent('addBusinessHours', null)">Add New</a></h2>


emitEvent(name, params) { EventBus.$emit( name , params ); }

在您的 business-hours 组件上,您导入 EventBus 并添加一个事件侦听器来侦听已调度的事件

created() { 
   EventBus.$on('addBusinessHours' , () => console.log('Business hours component received event from other component' );
}

这应该为您提供了使用 Vue 发送和接收事件的方法。 您还可以查看本教程以供参考,以更好地了解事件的工作原理。

https://medium.com/@andrejsabrickis/https-medium-com-andrejsabrickis-create-simple-eventbus-to-communicate-between-vue-js-components-cdc11cd59860

祝你好运

【讨论】:

    猜你喜欢
    • 2017-09-22
    • 2019-02-22
    • 2020-08-07
    • 1970-01-01
    • 2017-11-07
    • 2019-08-28
    • 2016-09-23
    • 2019-09-04
    • 2015-11-13
    相关资源
    最近更新 更多