VueJS understanding scoped slots(finally)
Just like many other things which I felt like I have understood, but as there is a saying, you truly learn by doing.
I implemented scoped slots in VueJS finally and understood their working.
How slots work:
Slots usually run in the same scope as the component in which you write them.
Example:
data-list.vue
<template> <div> <table-component> <template slot="filters"> <button type="button" class="btn btn-primary" data-toggle="button" @click="filterData" aria-pressed="false" autocomplete="off"> {{button}} </button> </template> </table-component> </div> </template> <script> //Vue instance related code </script>
We have a <table-component>
component which contains a slot.
In the slot,filterData
method is called when ever the button is clicked. This filterData
method should exist in scope of data-list.vue
component somewhere.
But what if you want to call filterData
method which is inside the <table-component>
Enter scoped slots
In your <table-component>
you can instead define the scope for the incoming slot.
Example:
table-component.vue
<template> <div> <div class="collapse" id="filters"> <slot name="filters" v-bind:fetchData="fetchData"></slot> </div> </div> </template> <script> // code table-component vue instance </script>
You can see that we have used v-bind:fetchData="fetchData"
on the slot inside the template.
This will make the fetchData
method to be available to any slot which is passed to this component.
Now we can change our code in data-list.vue to be:
<template> <div> <table-component :dataSource="this.dataSource" :columns="this.columns" :filters="this.filters" @setFiltersData="setFiltersData"> <template slot="filters" slot-scope="slotProps"> <button type="button" class="btn btn-primary" data-toggle="button" @click="slotProps.filterData" aria-pressed="false" autocomplete="off"> {{button}} </button> </template> </table-component> </div> </template>
We added slot-scope="slotProps"
, this will make slotProps
be available with the object passed in from the <table-component>
. We passed fetchData
from <table-component>
, which is now available to use within slot code as slotProps.fetchData
. We can use this now with our button click and it will call the correctfetchData
method i.e the fetchData
defined inside the table-component
component.
Yup it was simple 😉 (now I can say that)