[Vuejs]-Vue: Event Methods- Confusion

1đź‘Ť

âś…

In Vue 2, events only flow laterally or up, not down.

What you really want is to simply pass a prop into your components.

In the parent JS:

toggleMode () {
    this.editMode = ! this.editMode;
}

In the parent template:

<child-component-1 :editMode="editMode"></child-component-1>
...same for others...

Then simply accept editMode as a prop in each of your child components:

{
    props: ['editMode']
}

You can now use editMode within your child’s template. It’ll track the parent’s editMode, so no need for manual events/watchers.

👤Joseph Silber

1đź‘Ť

The way vue2 works is by having a one-direction flow of the data, from parent to child, so in your parent component you can have

<template>
 <child-component :isEditing="editMode"></child-component>
</template>

<script>

export default {
    methods: {
        toggleMode () {
          this.editMode = !this.editMode
          this.$emit('edit-mode-change', this.editMode)
        }
    }
}

and in child component you use props to get the data

Vue.component('child-component', {
  props: ['isEditing'],
  template: '<span>edit mode: {{ isEditing }}</span>'
})

we have cover the edit mode for the child. now if you want to send data from child to parent, then child needs to “emit” a signal to the parent, as props are “read only”

in child component you do at any point

someMethod() {
    this.$emit('editDone', dataEdited);
}

and in your parent component you “intercept” the message using on:

<template>
    <child-component 
        :isEditing="editMode"
        @editDone="someParentMethod"></child-component>
</template>

Greetings!

Leave a comment