Vue.js自定义事件问题

时间:2018-07-17 22:40:56

标签: events vue.js

我已经尝试解决了几个小时,但不确定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!
        }
    }
});

问题是,尽管我可以从组件区域内部发出关闭事件(在

元素上单击@),但无法从主vue对象的方法,也无法通过将this.$emit("open-modal-zone")粘贴到我想用来打开此模式组件的按钮中来实现。 这样就可以了,我想通过$emit函数直观地进行事件,但是在这种情况下,我该怎么做才能使open函数真正起作用?

1 个答案:

答案 0 :(得分:1)

Emit用于从子级到父级通信的事件。在根组件中发出事件没有任何意义

如果您需要父母与孩子之间的交流,则只需将道具从父母与孩子之间传递。 其他选项是全局事件总线。查看一些示例here

或者对于更复杂的情况,您可以使用vuex store

相关问题