简体   繁体   中英

How to access slot props in the created hook?

I'm trying to access properties I'm passing on to my slot. But my slotProps are undefined.

As I'm still new to Vue and I've read their docs I still can't seem to figure out why I can't access the props data.

Problem

I'm trying to access the slotProps in my child components created , but it's undefined

emphasized text

<template>
  <div>
    <slot :data="data" :loading="loading"></slot>
  </div>
</template>

Child

<template v-slot:default="slotProps">
  <div >

  </div>
</template>

<script>
export default {
  name: "child"
  created: function() {
    console.log("slotProps", slotProps);
  }
};
</script>

You can use this object to follow with your child property

demo: https://stackblitz.com/edit/vue-kkhwzc?file=src%2Fcomponents%2FHelloWorld.vue

Updated code Child

<template v-slot:default="slotProps">
  <div >

  </div>
</template>

<script>
export default {
  name: "child"
  created: function() {
    console.log("slotProps", this.slotProps);
  }
};
</script>

You do not need the created() life cycle hook to achieve what you want. There are few things to clear up:

  • What you are using is actually called scoped slots . They are useful because, unlike when using the default and named slots, the parent component can not access the data of its child component(s).

  • What you call a Child is actually the parent component.

Child.vue component should be something like this:

<template>
  <div>
    <main>
      <slot :data="data1" :loading="loading1" />
    </main>
  </div>
</template>

<script>
export default {
  name: 'Page',
  data () {
    return {
      data1: 'foo',
      loading1: 'bar'
    }
  }
}
</script>

In a Parent.vue component, you can access the data of the above component as follows:

<template>
  <child>
    <template v-slot="slotProps">
      {{ slotProps.data }},
      {{ slotProps.loading }}
    </template>
  </child>
</template>

<script>
import Child from '@/components/Child.vue'

export default {
  components: { Child }
}
</script>

Or you can also destruct the objects on the fly as follows:

<template>
  <child>
    <template v-slot="{data, loading }">
      {{ data }},
      {{ loading }}
    </template>
  </child>
</template>

<script>
import Child from '@/components/Child.vue'

export default {
  components: { Child }
}
</script>

This is the clean way to access data of a child component from the parent using scoped slots.

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