1
votes

I've been trying to figure this out for hours and I'm not sure what's wrong with my vue custom events.

<!-- 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!
        }
    }
});

The problem is that while I'm able to emit a close event from inside the component area, (the @click on the

element), I can't do so from my main vue object's methods, and neither can I do it by sticking this.$emit("open-modal-zone") it into the button which I'd like to use to open this modal component. So there you have it, I would like to intuitively do my events through the $emit functions, but what can I do to make my open function actually work in this case?

1
emit is for events from child to parent communication. What the meaning of emitting event from a root component? It wont do anything.Aldarund
So, what you say is that the "direct" way which I know to work above, is the best practice for communication from parent to child? Well, I can live with that if that's how it works! If you make it an answer, it can be the correct one if no one provides any arguments to the contrary or some example more verbose. Thanks.Vasily Hall

1 Answers

1
votes

Emit is for events from child to parent communication. There no meaning in emitting event in root component

If you need communicate from parent to child you just pass props from parent to child. Other options would be global event bus. See some example here

Or for more complex situation you could use vuex store.