3
votes

I'm using props to update my site content in the child component. This is basically working like this:

<child-component :updatedArray="updatedArray" />

then in the child component:

<template>
   {{updatedArray}}
   <div>{{computedArray}}</div>
</template>
<script>
   props: ['updatedArray'],
   ...
   computed: {
      computedArray() {
        if(this.updatedArray.item == "item one") {return "item one"}
       else {return "other item"}
       }
   }
</script>

Now this code should work in any case when I update updatedArray in my parent component. Then I see in my child component that my {{updatedArray}} is changing correctly, but my computedArray is not triggered and does not work.

Can I ask you why is this happening? Does computed do not work with every props update?

How should I correct my code?

edit: not duplicate I'm not mutating the prop, I rather only do a computed based on its value.

1
Help us out a little. The variable is named updatedArray but you are testing a key on it with updatedArray.item. What is updatedArray? An array or something else? - Mark
actually this is an object updatedArray: {item: "item1", item2: "item2"} etc.. - gileneusz
@Sphinx This is not the case, I'm not mutating the prop, I rather only do a computed based on its value - gileneusz
Hah, you need to bind with v-bind:updated-array="updatedArray" - Sphinx

1 Answers

9
votes

Your bind uses wrong name.

As Vue Guide describes:

HTML attribute names are case-insensitive, so browsers will interpret any uppercase characters as lowercase. That means when you’re using in-DOM templates, camelCased prop names need to use their kebab-cased (hyphen-delimited) equivalents

So you need to convert camelCase to kebab-case.

like v-bind:updated-array instead of v-bind:updatedArray.

Below is one working demo using kebab-case. You can change it to camelCase, then you will find not working.

Vue.component('child', {

  template: '<div><span style="background-color:green">{{ updatedArray }}</span><div style="background-color:red">{{computedArray}}</div></div>',
  props: ['updatedArray'],
  computed: {
    computedArray() {
      if(this.updatedArray.item.length > 0) {return this.updatedArray}
      else {return "other item"}
    }
  }
})

new Vue({
  el: '#app',
  data() {
    return {testArray: {
      'item': 'test',
      'prop1': 'a'
    }}
  },
  methods:{
    resetArray: function() {
      this.testArray['item'] += this.testArray['prop1'] + 'b'
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<button v-on:click="resetArray()">Click me</button>
<child v-bind:updated-array="testArray"></child>
</div>