Categories
Vue Answers

How to pass props using slots from parent to child with Vue.js?

Spread the love

Sometimes, we want to pass props using slots from parent to child with Vue.js.

In this article, we’ll look at how to pass props using slots from parent to child with Vue.js.

How to pass props using slots from parent to child with Vue.js?

To pass props using slots from parent to child with Vue.js, we need to create scoped slots.

For instance, in the parent component, we write

<template>
  <div>
    <h3>Parent:</h3>
    <slot :signal="parentVal"></slot>
  </div>
</template>

to add the signal prop and set it to parentVal.

Then in the child component, we write

<template>
  <div>
    <h3>Child {{ signal }}</h3>
  </div>
</template>

<script>
//...
export default {
  //...
  props: ["signal"],
  //...
};
</script>

to make it accept the signal prop.

Then in the component that wraps the parent around the child components, we write

<template>
  <div>
    <my-parent>
      <template slot-scope="{ signal }">
        <my-child :signal="signal"></my-child>
        <my-child :signal="signal"></my-child>
      </template>
    </my-parent>
  </div>
</template>

to wrap my-parent the my-child component instances.

We get the signal slot prop value with slot-scope="{ signal }".

And then we set signal as the value of the signal prop of the my-child instances.

Conclusion

To pass props using slots from parent to child with Vue.js, we need to create scoped slots.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *