Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue - pass reactive prop from parent to child? [closed]

I know this has been asked a lot here in different forms, but I'm having trouble getting a child to be reactive to changes made in the parent. I have tried key changing, but that doesn't seem to work in this case.

Shouldn't a child component know to re-render itself when a prop it is receiving has changed?

For example (this is not my exact component, just an example of the data flow):

<template>
  <div id="parent">
    <h1>Sort By</h1>
    <button @click"handleClick('alpha')">Alphabetical</button>
    <button @click"handleClick('price')">Price</button>
    <ChildComponent :sortBy="sortBy" :key="keyChangingDoesntWork" /> // doesn't update when 'sortBy' changes.
  </div>
</template>
<script>
// ...
name: "parent",
data(){
  return{
    sortBy: 'alpha',
  }
},
methods: {
  handleClick(by){
    if (by === 'alpha') {
      this.sortBy = 'alpha'
    } else {
      this.sortBy = 'price'
    }
  }
}
</script>

// child

<script>
  props: {
    sortBy: String
  }
  updated() {
    console.log(this.sortBy); // need this to change when buttons are clicked in parent
  }
</script>
like image 216
Kirk Ross Avatar asked Sep 12 '25 00:09

Kirk Ross


1 Answers

You can watch props as below

Parent:

    <template>
    <div id="parent">
        <h1>Sort By</h1>
        <button @click="handleClick('alpha')">Alphabetical</button>
        <button @click="handleClick('price')">Price</button>
    
        <ChildComponent v-bind:sortBy="sortBy" />
    </div>
    </template>
    <script>
    import ChildComponent from './ChildComponent';
    export default {
        name: "parent",
        data() {
            return {
                sortBy: 'alpha',
                keyChangingDoesntWork: 1
            }
        },
        components: {
            'ChildComponent': ChildComponent
        },
        methods: {
            handleClick(by) {
                if (by === 'alpha') {
                    this.sortBy = 'alpha'
                } else {
                    this.sortBy = 'price'
                }
                return this.sortBy;
            }
        },
    }
    </script>

Child:

    <template>
    <div>
        <h5>Child: {{ sortBy }}</h5>
    </div>
    <!--  prop change watch-->
    </template>
    <script>
    export default {
      props: {
        sortBy: String,
      },
      watch: {
        sortBy: function (newVal, oldVal) {
          // watch it
          console.log("Prop changed: ", newVal, " | was: ", oldVal);
        },
      },
    };
    </script>
like image 54
Manoj Avatar answered Sep 13 '25 15:09

Manoj