javascript - Vue.js $从父组件发出事件并在组件(子组件)上接收它

标签 javascript vue.js

我似乎无法让它工作!

我已将 $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()">

不确定这是否会影响它,但我的营业时间组件位于另一个组件内。

最佳答案

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

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

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

然后导入到您希望从中发出值的组件:

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

然后您分派(dispatch)事件

<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 并添加一个事件监听器来监听已分派(dispatch)的事件

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

祝你好运

关于javascript - Vue.js $从父组件发出事件并在组件(子组件)上接收它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53100339/

相关文章:

javascript - 如何查看创建组件后初始化的文档变量?

vue.js - Cytoscape 布局 - 处理锁定节点

javascript - 如何使用 VueJS/Typescript 导入 JSON 文件?

javascript - PL/SQL CHR(13)||CHR(10) 返回 0

javascript - Node.js-事件.js :154 throw err write EPIPE; Program Crashing

javascript - 细胞景观 : TypeError even with the tutorial

javascript - 如何将Vue数据传递到axios post请求中?

javascript - AngularJS:将部分生成的值存储到 Controller 中

javascript - 有人可以从事件循环的 Angular 向我解释一下吗?

vue.js - 在 Pinia 中使用 Socket.io 时出现问题