[Vue] Vue 3.5 Reactive Props Destructure

Reactive props destructure is the highlight feature of Vue 3.5.

It allows you to destructure props while maintaining their reactivity:

const { foo } = defineProps<{ foo: string }>()

Previously in Vue.js, destructuring props would cause them to lose reactivity. Now they remain reactive, allowing you to use them with built-in functions like watch and computed.

 

But with watch, you have to wrap the prop in a function.

watch(() => foo, () => {
  console.log('foo is changed')
})

That’s because the destructured prop variable will be automatically compiled to something like this for runtime:

watch(() => props.foo, () => {
  console.log('foo is changed')
})

So if you didn’t wrap this in a function, the watch would just be watching a property of the propsprops.foo is just a static value, it would not be reactive.

But if we wrap it in a function, watch will be able to assess the value of this prop by running the function to get the prop’s current value.

Reactive props destructure improves developer experience (DX) by eliminating the need to prefix props with props. in the <script> section.

 

Additionally, you can set the default value for a prop like this:

const { foo = 'Foo' } = defineProps<{ foo: string }>()

So you won’t need to rely on withDefaults to set the default values for props.

That’s it for reactive prop destructure from Vue 3.5. If you want to learn more about this feature you can check out the documentation for that.

 

<script setup lang="ts">
import { watch, computed } fron 'vue'

const { foo = 'Foo' } = defineProps<{ foo: string }>()

watch(props.foo, () => {
  console.log('foo is changed')
})

const bar = computed(() => foo + foo)
</script>

<template>
  <p>{{ foo }}</p>
</template>

 

posted @ 2025-03-11 15:44  Zhentiw  阅读(36)  评论(0)    收藏  举报