Vue.js 自定义事件问题
Posted
技术标签:
【中文标题】Vue.js 自定义事件问题【英文标题】:Vue.js custom event issue 【发布时间】:2018-12-25 17:32:51 【问题描述】:我已经尝试解决这个问题好几个小时了,但我不确定我的 vue 自定义事件出了什么问题。
<!-- part of the vue template: the main element -->
<!-- not working <button @click='$emit(\"open-modal-zone\")'></button> -->
<!-- not working <button @click='activateFilterModalViaEmit'></button> -->
<modal-zone :filter-obj='filterObj' @open-modal-zone='modalActive=true' @close-modal-zone='modalActive=false' v-if='modalActive' ></modal-zone>
<!-- the component in question -->
Vue.component('modal-zone',
props : ["filterObj", "modalActive"],
template: "<div id='modal-zone'>" +
"<p @click='$emit(\"close-modal-zone\")'>Close</p>" +
"<filter-modal-dialog-controls :filter-obj='filterObj'></filter-modal-dialog-controls>" +
"</div>"
);
<!-- filter-dialog-controls component omitted (I haven't gotten that far yet) -->
// the vue js of my app
var v = new Vue(
el : "#editing-div",
data :
modalActive : false,
filterObj :
filterModalActive : false
,
methods :
activateFilterModalViaEmit : function()
this.$emit("open-modal-zone"); //why doesn't this work?
activateFilterModal : function()
this.modalActive = true; // this works.. but I want $emit!
);
问题是,虽然我能够从组件区域内部发出关闭事件,(@click
元素),我不能从我的主要 vue 对象的方法中这样做,我也不能通过将this.$emit("open-modal-zone")
粘贴到我想用来打开这个模态组件的按钮中来做到这一点。
好了,我想通过$emit
函数直观地执行我的事件,但是在这种情况下,我该怎么做才能使我的开放函数真正起作用?
【问题讨论】:
emit 用于从子到父通信的事件。从根组件发出事件是什么意思?它不会做任何事情。 那么,你说的是我知道上面的“直接”工作方式,是父母与孩子沟通的最佳实践吗?好吧,如果它是这样工作的,我可以忍受!如果您将其作为答案,则如果没有人提供任何相反的论据或更详细的示例,则它可能是正确的答案。谢谢。 【参考方案1】:Emit 用于从子到父通信的事件。在根组件中发出事件没有意义
如果您需要父母与孩子之间的交流,您只需将道具从父母传递给孩子。 其他选择是全局事件总线。看一些例子here
或者对于更复杂的情况,您可以使用vuex store。
【讨论】:
以上是关于Vue.js 自定义事件问题的主要内容,如果未能解决你的问题,请参考以下文章
Vue.js 绑定到名称中带有点的 DOM 自定义事件(如引导事件)