How to use the slots in Vue.js
In this tutorial, we will learn about how to use the slots in vue.js with the help of examples.
What are Slots?
Slots helps us to pass the data between opening and closing component tags.
In vue.js props are used to pass the data to its child components, but it is hard to pass when we have a complex code. In such cases slots can be used.
Let’s create a new component called Post
by adding the <slot>
element.
<template>
<div>
<slot></slot> </div>
</template>
<script>
export default{
}
</script>
Now, if we pass any content between the Post
component opening and closing tags that are rendered in the place of <slot></slot>
element.
<template>
<div>
<Post>
<h1>What is Lorem Ipsum?</h1> <p> What is Lorem Ipsum?Lorem Ipsum is simply dummy text of the printing andtypesetting industry.Lorem Ipsum has been the industry's standard dummy. </p> </Post>
</div>
</template>
<script>
import Post from "./components/Post";
export default {
components: {
Post
}
};
</script>
Output:
Named Slots
Sometimes, we need to pass the data to a specific places in such cases named slots can be used.
The named slots can be created by adding a name
attribute to the <slot>
element.
<template>
<div>
<slot name="title"></slot> <slot name="description"></slot> </div>
</template>
<script>
export default{
}
</script>
To pass the content to the named slots we need to use v-slot
directive on template providing slot name as v-slot
argument.
<template>
<div>
<Post>
<template v-slot:name> <h1>What is Lorem Ipsum?</h1>
</template>
<template v-slot:description> <p>
What is Lorem Ipsum?Lorem Ipsum is simply dummy text of the printing
andtypesetting industry.Lorem Ipsum has been the industry's standard
dummy.
</p>
</template>
</Post>
</div>
</template>
<script>
import Post from "./components/Post";
export default {
components: {
Post
}
};
</script>
Fallback data
In some cases, we can use fallback data (aka default) when data is not passed to a slot.
For example:
<template>
<button>
<slot>Submit</slot> </button>
</template>
In the above component, we have added a Submit
text inside a slot
element.
Now, If we use a my-button
component without passing any data we can see
the fallback data Submit
text is rendered inside the button.
<template>
<div>
<my-button></my-button> </div>
</template>
<script>
import Mybutton from "./components/my-button.vue";
export default {
components: {
"my-button": Mybutton
}
};
</script>
Output of rendered html:
<div>
<button>Submit</button></div>
But, if we pass data to the my-button
component fallback data is replaced.
<template>
<div>
<my-button>Add</my-button> </div>
</template>
<script>
import Mybutton from "./components/my-button.vue";
export default {
components: {
"my-button": Mybutton
}
};
</script>
Output of rendered html:
<div>
<button>Add</button></div>