happenask
happenask

Reputation: 1084

VueJs Updating data Issue when not object type props change

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.

Upvotes: 2

Views: 456

Answers (1)

Phil
Phil

Reputation: 164766

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>

Upvotes: 1

Related Questions