Dave
Dave

Reputation: 339

Computed Property on Dynamic Prop Object

I have a parent component that passes an object to a child, and that child has a computed property that is reliant on the object prop.

I can see that as I update the prop object in the parent that the prop is updated within the child but the computed property is only computed once upon loading and then never re-computes, same goes for watchers even if I use 'deep', the computed property or watched object never gets triggered.

Here is a code example (assume orderData is just some object)

orderData {'test': 5}

Parent

OrderForm(
  :orderData='orderData'
)

Child

  computed: {
    orderJson() {
      console.log('computed')
      return JSON.stringify(this.orderData)
    }
  },
  props: ['orderData']

I have also tried

  watch: {
    orderData: {
      handler(val, oldval) {
        console.log('hanlded')
        this.orderJson = JSON.stringify(val)
      },
      deep: true
    }
  }

in both cases I see no updates to orderJson in my vue inspector, any ideas why?

Upvotes: 3

Views: 839

Answers (1)

Matt
Matt

Reputation: 44058

Try logging out this.orderJson in your orderData watcher:

  watch: {
    orderData: {
      handler(val, oldval) {
        console.log(this.orderJson);
      },
      deep: true
    }
  }

Computed props aren't updated until they are used somewhere

EDIT: Here's a simplified example that I think does what you want, though I'm not 100% clear: https://codepen.io/codingcampbell/pen/219e1377e764659c16ebb8cefbca9ce9

Upvotes: 1

Related Questions