Quốc Cường
Quốc Cường

Reputation: 495

About Scoped Slots in vuejs

I'm learning vuejs and reading about 'Slots'. I have understood it, how to use it. But I still have a concern about 'Scoped Slots' and I will talk about it with the code I have taken from vue documentation.

Here is the code

/* this is child component */
<span>
  <slot v-bind:user="user">
    {{ user.lastName }}
  </slot>
</span>
/* father component */
<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>
</current-user>

My question:
the code above make 'user' available to the slot content in the parent. That means the 'data' attribute in the child component will be as follows:

data(){
  return {
     user: {
       firstName: 'fname',
       lastName: 'lname'
     }
  }
}

ok, I understood this part and practiced with it. But what if I change the 'data' attribute to:

data(){
  return {
     firstName: 'fname',
     lastName: 'lname'
  }
}

I still don't know how to work with the 'Scoped Slots' in the above case (without the 'user').

Upvotes: 0

Views: 57

Answers (1)

skirtle
skirtle

Reputation: 29132

This is your original code:

<slot v-bind:user="user">

It's potentially confusing because there are two things called user here. The v-bind:user part is going to create a user property within the slotProps object. The other part, ="user", just assigns a value to that property. The fact that this value is also coming from a property called user makes this example somewhat difficult to follow.

For your second example, you could maybe do something like this:

<slot v-bind:user="{ firstName, lastName }">

Note that { firstName, lastName } is a shorthand for { firstName: firstName, lastName: lastName }. It's just creating an object with two properties. The values for those two properties are coming from your data.

Again this is creating a property called user within the slotProps but this time the value is an object that is being created on the fly.

Upvotes: 1

Related Questions