2

I am using VueJS and what I want to do is update data everytime props change.

my code is blow

template code:

<div id="app">
<input type="text" v-model="hello">
<my-component :message="hello"></message>
</div>   

vue code:

var Child = {
template: '<div>props: {{message}} data: {{msg.value}}</div>',
props: {
  message: {
    type: String
   }
},
data: function () {
  return {
    msg: {
      value: this.message
    }
  }
 }
}
new Vue({
  el: '#app',    
data: function () {
  return {
    hello: 'Hello World !!!'
  }
},
components: {
  myComponent: Child
 }
})

result:

enter image description here

I found out that String Type Props passed by parent component doesn't update data.

I think it seems like observer issue. please give any idea.

happenask
  • 1,062
  • 3
  • 14
  • 21
  • Why are you duplicating the `prop` into the component `data`? Unless you plan on altering the copy within your component, there's really no need – Phil Jan 31 '18 at 02:28
  • @Phil above code is just example code, I absolutely need it in the project I'm working on. – happenask Jan 31 '18 at 04:45
  • 1
    Is there a reason you can't use a computed property for `msg`? That's typically the recommended approach ~ https://vuejs.org/v2/guide/computed.html – Phil Jan 31 '18 at 05:19
  • 1
    It's also not clear from your example why you need this at all. Perhaps your example could include something to explain further? – Phil Jan 31 '18 at 05:23

1 Answers1

1

Sounds like you want to watch the prop and update the data. For example

watch: {
  message (newValue, oldValue) {
    this.msg.value = newValue
  }
}

Note that this will overwrite any changes you've made to msg.value when message changes and I'm not entirely sure why you'd want to do that.

var Child = {
  template: `<section>
    <div>props: {{message}} data: {{msg.value}}</div>
    <button @click="msg.value = 'Goodbye, cruel world'">Bye</button>
  </section>`,
  props: {
    message: {
      type: String
    }
  },
  data() {
    return {
      msg: {
        value: this.message
      }
    }
  },
  watch: {
    message(newValue, oldValue) {
      this.msg.value = newValue
    }
  }
}
new Vue({
  el: '#app',
  data: {
    hello: 'Hello World !!!'
  },
  components: {
    myComponent: Child
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>
<div id="app">
  <input type="text" v-model="hello">
  <my-component :message="hello" />
</div>
Phil
  • 157,677
  • 23
  • 242
  • 245
  • I already know how to use watch, I just wanted to know reason why string type props can't update data, in case passing object type props, data get updated. may be it is observer issue. anyway thanks for your help!! – happenask Feb 02 '18 at 09:14
  • @happenask I think you should read this ~ https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – Phil Feb 05 '18 at 01:11