Home > Software engineering >  Passing a prop to child component isn't working on Vue 3
Passing a prop to child component isn't working on Vue 3

Time:10-15

I have this simple file:

<script setup>
import { ref } from 'vue'
import TheHeader from '@/components/_headerbar/TheHeader.vue'
import TheSidebar from '@/components/_sidebar/TheSidebar.vue'

const sidebarState = ref(false)

const onSidebarToggle = () => {
  sidebarState.value = !sidebarState.value
}
</script>

<template>
  <QLayout view="hHh lpR fFf"> 
    <TheHeader @toggle-sidebar="onSidebarToggle" />
    <TheSidebar :sidebar-state="sidebarState.value" />

    <QPageContainer>
      <RouterView v-slot="{ Component }">
        <component :is="Component" />
      </RouterView>
    </QPageContainer>
  </QLayout>
</template>

The sidebarState variable here updates just fine everytime the event toggle-sidebar is fired, but the prop that recieve its value never updates and I just don't know what is happening.

This is the TheSidebar.vue file:

<script setup>
const props = defineProps({
  sidebarState: {
    type: Boolean,
    default: true
  }
})
</script>

<template>
  <QDrawer
    :model-value="props.sidebarState"
    show-if-above
    side="left"
    bordered
  >
    content
  </QDrawer>
</template>

Debugging here I can tell the sidebarState prop from TheSidebar.vue file just never changes, even though the data prop of TheHeader.vue sidebarState changes just normally.

What am I doing wrong?

CodePudding user response:

You shouldn't use .value in template with refs of top-level properties. The value is automatically unwrapped for you (note: make sure the toggle in the top left of the docs is switched from "Options" to "Composition" for link to correctly work).

Simply remove .value and your code should work

<TheSidebar :sidebar-state="sidebarState" />
  • Related