Vue 3— How to destructure props and maintain reactivity
Vue 3 saw the introduction of the Composition API, introducing new ways to define reactive properties. Reactive properties provide many benefits: simplified state management, efficient re-rendering and declarative data binding. Amongst these properties, props
also provides a reactive object of values.
There are some instances however where these reactive properties can cause some hiccups. Destructuring props is one of them, causing destructured prop variables to lose reactivity. This article will show you how to configure your Vite project so that you can destructure Vue props and maintain their reactivity.
Problem and previous workarounds
As you can see from the code snippets below, the problem with destructuring the props
object is that destructured variables lose reactivity and future changes to the prop won’t be reflected.
In the example below, the setTimeout
function in User.vue
changes the value of name
after one second which is passed to Greeting.vue
as a prop. The destructured name
prop in the Greeting.vue
component is not updated to reflect this change, and Hello, Frodo
is still rendered.
// User.vue
<script setup>
import { ref } from 'vue'
import Greeting from './Greeting.vue'
const name = ref('Frodo')
setTimeout(()…