3

I have a Vue component with a single prop, which is an object. When a property in this object is changed, it doesn't seem to be updating in the Vue template.

Here is a simplified version of the component:

<template>
  <p>{{ item.quantity }}</p>
</template>

<script>
  export default {
    props: {
      item: {
        required: true,
        type: Object
      }
    }
  }
</script>

Using vue-devtools in Google Chrome, I can see the quantity property in my item object is being updated, but the template still only renders the default value (1).

Is there something I need to do to make Vue watch nested properties or something?

3
  • you can create a new object from the old one and then change the prop value, so the object ref changes Commented Mar 7, 2018 at 12:57
  • @h1b9b Could you explain more in an answer? Commented Mar 7, 2018 at 13:00
  • I am not a vue.js specialist but if the component checks only object ref (a == b) and not a deepEqual, you need a new object so it can detect the change. somme thing like newItem = {...item, quantity: newquantity } should work Commented Mar 7, 2018 at 13:10

1 Answer 1

1

The issue is that the component is not aware that it should re-render when there is a change in the props. You could use a computed property which returns the props value and use the computed property value.

<template>
  <p>{{ quantity }}</p>
</template>

<script>
  export default {
    props: {
      item: {
        required: true,
        type: Object
      }
    }

    computed: {
        quantity: function() {
            return this.item.quantity
        }
    }
  }
</script>
Sign up to request clarification or add additional context in comments.

5 Comments

I've tried using a computed value, for both the item prop and specifically item.quantity, but the template still doesn't seem to update.
I understand your value is coming from the vuex store. Have you tried using mapState to get the state from the store? You could try using the mapState in the computed properties.
The component represents a single item from an array of items in the Vuex store. The item is a line item in an order. I'm trying to get the displayed quantity to update if that item's quantity is updated in the Vuex store.
So from what I understand there is a parent component that renders an array of item components. If the parent component is mapped to the Vuex store and passes the mapped values as props to the children, that would trigger a re-render of the children if the child uses the prop in computed or data.
This seems like the right approach. There is also the deep watch option. I just went through this same issue last week and my real problem was how I was updating the original array in vuex. vuejs.org/v2/guide/list.html#Caveats

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.