vue.jsvuejs3vue-componentvue-props

Vuejs child component props does not update when parent component update props value


I have a parent and child component setup, whenever i pass an object property to my child component, it only picks up the initial value and does not further update when changes are made from the parent component, but if i pass the whole object has a prop to the child component, it updates as the parent component updates. Here is an example of my setup (note: i am using the composition api)

In my parent component i have the following setup

<template>
    <select v-model="form.country">
      <option
        v-for="(data, idx) in countryList"
      >
        {{ data.name }}
      </option>
    </select>
    
    <ChildComponent :country="form.Country" />
</template>

<script setup>
   let form = reactive({
      Country:"",
      // ...other object properties
    })
<script/>

My child component is as such

<template>
   //.....
</template>
<script setup>
   const {country} = defineProps('country')

   watch(country, ()=>{
     //...does not trigger on property change
   }
<script\>

But if i pass the full object as the props e.g

  <template>   
   <ChildComponent :country="form" /> 
  </template>

the watch function in the child component triggers anytime the properties of form is updated in the parent component

I have gone through vuejs docs, but couldn't find a solution, the only method that works is by passing the whole object, but why do i have to pass the whole object when i just want to work with a single property


Solution

  • In child component you should use computed for props. Example:

    <template>
       //.....
    </template>
    <script setup>
       const props = defineProps(["country"]);
       const selectedCountry = computed(() => props.country);
    <script\>
    

    You can read more information in https://vuejs.org/guide/components/props.html