Reputation: 2897
The code below should display my prop default value ("test") since it received no other value. Yet it displays nothing. Why not?
<template>
<div>
{{ propValue }}
</div>
</template>
<script setup lang="ts">
import { defineProps } from "vue"
const props = defineProps<{
myProp: {
type: string
default: "test"
}
}>()
const propValue = props.myProp
</script>
Upvotes: 0
Views: 119
Reputation: 14739
There are two reasons why.
withDefaults
macro (you also need to separately declare a Props interface). Side note: I would not use the alternative experimental "Reactivity Transform" solution noted in the docs (it's being removed soon)export interface Props {
myProp?: string;
}
const props = withDefaults(defineProps<Props>(), {
myProp: 'test'
});
props
is a reactive object, and when you assign a single property of props
to a new variable, the reactivity breaks. In order to maintain reactivity and stay synced with any future changes to props, use the toRef functionconst propValue = toRef(props, 'myProp');
and be sure to import it: import { defineProps, toRef } from 'vue';
Upvotes: 0