JayK23
JayK23

Reputation: 263

Vue - refresh value of data i'm passing to Component

I'm passing a variable from a parent to a child component like so:

parent Component

<template>
  <div>
    <childComponent :lastPrice="lastPrice"></childComponent>
  </div>
</template>

<script>

export default {

  props:{

    lastPrice:{
      type:Number,
      default: 0
    }

  
  },

  mounted() {

    this.fetchLastPrice()
  },

  methods: {
    fetchLastPrice(){
      fetch('MY-API')
        .then(response => response.json())
        .then(data => {
          this.lastPrice = data['lastPrice']
      })
    }
  }

}

</script>

And then i have the childComponent

<template>
  <div>
    <h1>Last price: {{lastPrice}}</h1>
  </div>
</template>
     
<script>

export default {

  props:{

    lastPrice:{
      type:Number,
      default: '',
    }

  },

  mounted() {
    console.log('Mounted')
  },

  methods: {
    ...
  }
}

</script>

In the parent component, i define lastPrice and i pass it to the child component. Then i change the value of lastPrice in the parent component. The problem with my code is that, in the child component, the value of lastPrice is always 0. Is there any way i can make it reactive? I would like to avoid using Vuex as it's overkill for this task, if possible. Thanks in advance for any advice

Upvotes: 0

Views: 292

Answers (2)

Jo.
Jo.

Reputation: 74

In your Parent component you defined lastPrice as props, so you can not mutate it to pass it to you Child component.

Here a sandBox with a functional example:

https://codesandbox.io/s/nice-faraday-50liu?file=/src/components/Parent.vue

Upvotes: 1

Pierre Said
Pierre Said

Reputation: 3840

In the parent component you defined a prop instead of some data.

Try this instead in the parent component:

data() {
  return { lastPrice: 0 }
}

Upvotes: 1

Related Questions