2
votes

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.

1
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
@Phil above code is just example code, I absolutely need it in the project I'm working on. - happenask
Is there a reason you can't use a computed property for msg? That's typically the recommended approach ~ vuejs.org/v2/guide/computed.html - Phil
It's also not clear from your example why you need this at all. Perhaps your example could include something to explain further? - Phil

1 Answers

1
votes

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/[email protected]/dist/vue.js"></script>
<div id="app">
  <input type="text" v-model="hello">
  <my-component :message="hello" />
</div>