-
-
Notifications
You must be signed in to change notification settings - Fork 9k
Description
Vue version
3.5.24
Link to minimal reproduction
Steps to reproduce
Child.vue
<script setup lang="ts">
import { onMounted } from 'vue';
interface Props {
myBool?: boolean;
}
const props = defineProps<Props>();
const { myBool = true } = props;
onMounted(() => {
console.log(myBool); // shows false
})
</script>
Parent.vue
<template>
<Child/>
</template>
<script setup lang="ts">
import Child from "./Child.vue";
What is expected?
Inside the onMounted hook, myBool should be true
What is actually happening?
Inside the onMounted hook, myBool is false
System Info
Any additional comments?
With typescript, this way of providing default value is nice: const { myBool = true } = props;. But for optional boolean that I want to default to true, this way of providing default value doesn't work. Do we really need to fallback to withDefaults and do something like this if we also want reactive props destructuring?
Child.vue
<script setup lang="ts">
import { ref, onMounted } from 'vue';
interface Props {
myBool?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
myBool: true,
});
const { myBool } = props;
onMounted(() => {
console.log(myBool); // shows true
})
</script>
The fact that giving default values to other types like const { myNum = 0 } = props; works, but const { myBool = true } = props; doesn't, kinda makes this syntax something I wouldn't recommend. I think either there should be a way that consistently provides default values like this, or just don't recommend this, and say that we should use withDefaults instead.
https://vuejs.org/api/sfc-script-setup.html#default-props-values-when-using-type-declaration
In the current state, I would modify this part and say use withDefaults even for vue 3.5+, don't declare default values simply with Reactive Props Destructure.

In the long run, I would hope const { myBool = true } = props; to work.