Home > Back-end >  How to send data to parent component using v-slot in vue
How to send data to parent component using v-slot in vue

Time:12-23

I am trying to use slot-scopes in my component but I am not really successful on these. So in general what I am trying to do is I have a parent component and as a slot I am sending another component (child-component). In child component there is a button which changes the boolean.

So child component is:

<button @click="changeEditMode">Change edit mode</c-button>

methods: {
   changeEditMode() {
      this.$emit('edit-mode', true);
    },
}

Parent component:

<div>
        <slot :edit-mode="editMode"></slot>
      </div>

props: {
    editMode: {
      type: Boolean,
      required: true,
    },
  },

And here where both of them exist:

<parent-component>
              <template v-slot="scope">
                {{ scope.editMode }}
                <child-component
                  @edit-mode="scope.editMode"
                />
              </template>
            </parent-component>

    data() {
        return {
          editMode: false,
        };
      },

So I am expecting the value of {{ scope.editMode }} will change when I click the button but nothing changes. So where I am doing wrong?

CodePudding user response:

If you simply want to update the editMode variable in your third component then you don't need to use scoped slot. Simply use named slots and you can update the data like this-

Parent component-
Give your slot a name "scope" where you are planning to inject the data.

<div>
  <slot name="scope"></slot>
</div>

Another component-
Put your child component inside the named slot of the parent and simply listen to the emitted event from the child and update your editMode variable.

<parent-component>
  <template #scope>
    {{ editMode }}
    <child-component
      @edit-mode="editMode = $event"
    />
  </template>
</parent-component>

data() {
  return {
    editMode: false,
  };
},

Now, as in the question you are passing data to the slots (which I feels less required according to your use case), you can do it like this-

Parent component-

<div>
  <slot :editMode="editMode"></slot>
</div>

data() {
  return {
    editMode: false,
  }
}

Another component-

<parent-component>
  <template #scope="scopeProps">
    {{ scopeProps }}
  </template>
</parent-component>

To know more about the named slots and pass data to named slots, read here- https://vuejs.org/guide/components/slots.html#named-slots

  • Related