简体   繁体   中英

Pass props to a slot from the Child with Vue

I've been thinking on passing a prop content to a slot from the child

This is my solution:

<div id="app">

  <example>
    <template #example-body="{ exampleText }">
      <p>{{ exampleText }}</p>
    </template>
  </example>
  
</div>
Vue.component('example', {
  data () {
    return {
      exampleText: "This is a sample"
    }
  },
  
  template: `
    <div>
      <slot name="example-body" v-bind:exampleText="exampleText" />
    </div>`
})

new Vue({
  el: '#app'
})

https://codepen.io/sirlouen/pen/OJWMRba

It works, but I don't feel it's enough elegant.

How could I improve it?

In fact, if I'm sincere, I don't understand why this works. I've been testing like a hundred options until I made it work, but not sure why, specially the { } within the template.

If someone could provide me more info it would be great.

Originally you've:

<template #example-body="slotProps">
  <p>{{ slotProps.exampleText }}</p>
</template>

but we could destruct that object which is ES6 syntax:

<template #example-body="{ exampleText }">
  <p>{{ exampleText }}</p>
</template>

Here is what I was looking for

<div id="app">

  <example>
    <template #example-body="slotProperties">
      <p>{{ slotProperties.passedExample }}</p>
    </template>
  </example>
  
</div>
Vue.component('example', {
  data () {
    return {
      exampleText: "This is a sample"
    }
  },
  
  template: `
    <div>
      <slot name="example-body" v-bind:passedExample="exampleText" />
    </div>`
})

new Vue({
  el: '#app'
})

https://codepen.io/sirlouen/pen/GRroOBv

As I mentioned in the comments above, what I did not had clear, was the relationship between the binded element in the slot and the result in the HTML.

What I've found strange and interesting, is that the passedExample prop is part of an object from the slot, not the variable itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM