Skip to content
Advertisement

v-slot is always undefined in VueJS

Here is the problem. Root view:

<template>
  <div class="home">
    <Grid :rows=3 :cols=4>
      <GridItem :x=1 :y=1 />
      <GridItem :x=2 :y=1 />
    </Grid>
  </div>
</template>

<script>
import Grid from '@/components/Grid'
import GridItem from '@/components/GridItem'

export default {
  name: 'Home',
  components: {
    Grid,
    GridItem
  }
}
</script>

Grid component (container):

<template>
  <div class="grid">
    <slot v-bind="testData"></slot>
  </div>
</template>

<script>
export default {
  name: 'Grid',
  data() {
    return {
      testData: 'test'
    }
  },
  props: {
    rows: Number,
    cols: Number
  }
}
</script>

And finally grid item component:

<template v-slot="slotProps">
  <div class="grid-item">
      {{x}} {{y}} {{slotProps.testData}}
  </div>
</template>

<script>
export default {
  name: 'GridItem',
  props: {
    x: Number,
    y: Number
  }
}
</script>

I’m getting the error: GridItem.vue Uncaught (in promise) TypeError: Cannot read property ‘testData’ of undefined. I’m cracked my head trying to understand what’s going wrong. Need help, thanks for your time.

Advertisement

Answer

Get your slot props in Home component:

<template>
  <div class="home">
    <Grid :rows=3 :cols=4 v-slot="{ testData }">
      <GridItem :x=1 :y=1 :test-data="testData" />
      <GridItem :x=2 :y=1 :test-data="testData" />
    </Grid>
  </div>
</template>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement