Ridan
Ridan

Reputation: 349

How to pass data to a slot in vue2.6

Here is the hierarchy. Component A is the parent of Component B. Component B is the parent of Component C.

Component A looks like this:

<template>
  <component-b>
    <component-c>
  </component-b>
</template>

Component B:

<template>
  <input type=text/>
  <slot>
  </slot>
</template>

I need component B to pass data from it's context into component C. I am not sure how to do this with slots. Component B has an input box and as the user types I need that data to be bound to the slot, which in turn will cause component C to take that variable and use it within itself.

Upvotes: 0

Views: 2122

Answers (2)

Phil
Phil

Reputation: 164766

Have a look at scoped slots ~ https://v2.vuejs.org/v2/guide/components-slots.html#Scoped-Slots

For example, in ComponentB...

<template>
  <div>
    <input type="text" v-model="textValue" />
    <slot :text="textValue"></slot>
  </div>
</template>

Here, I've bound ComponentB's textValue data property to a slot-scoped property named text.

In ComponentA, you can access this via the v-slot directive

<component-b v-slot="{ text }">
  <component-c :some-prop="text" />
</component-b>

Demo ~ https://jsfiddle.net/uj05gqtm/

Upvotes: 3

Michael Mano
Michael Mano

Reputation: 3440

You can emit the value from the child.

component A

<template>
  <component-b @inputChange="useValue">
    <component-c :data="valueEmited">
  </component-b>
</template>
<script>
export default {
  data() {
    return {
      valueEmited: '',
    };
  },
  methods: {
    useValue(value) {
      console.log('this is the data emited from the child', value);
      this.valueEmited = value;
    }
  },
}
</script>

component b

<template>
  <input type=text v-model="text" @change="emitThisValue"/>
  <slot>
  </slot>
</template>
<script>
export default {
  data() {
    return {
      text: '',
    };
  },
  methods: {
    emitThisValue() {
      this.$emit('inputChange', this.text);
    }
  },
}
</script>

You can then pass the value to component C as a prop

https://v2.vuejs.org/v2/guide/components.html#Emitting-a-Value-With-an-Event

Upvotes: 0

Related Questions