David
David

Reputation: 336

how to update vuejs component from parent

I'm a little lost in VueJs, I try to make a vue with data updated by component and the Vue.

I understood how to update parent values with $emit.

Can someone tel if this is possible

Html Code

<div id="app2" v-cloak>
  <p>{{labels.lbl1}}: {{values.value}}</p>
  how direct set {{labels.lbl1}} here: <input type="text" v-model:value="values.value"> can set the child value?
  <hr/>
  <child2 v-model:value="values.value" v-bind:lbl="labels.lbl1"></child2>
</div>

<template id="child2">
  <div>
     Set {{internallbl1}} in child:
     <input type="text" v-model="internalValue" >
     <p>Value : {{value}}</p>
  </div>
</template>

Js Code:

Vue.component('child2', {
  template: '#child2',

  //The child has a prop named 'value'. v-model will automatically bind to this prop
  props: ['value','lbl'],
  data: function() {
    return {
      internalValue: '',
      internallbl1:''
    }
  },
  watch: {
    'internalValue': function() {
      // When the internal value changes, we $emit an event. Because this event is 
      // named 'input', v-model will automatically update the parent value
      this.$emit('input', this.internalValue);
    }
  },
  created: function() {
    // We initially sync the internalValue with the value passed in by the parent
    this.internalValue = this.value;
    this.internallbl1 = this.lbl;
  }
});
new Vue({
  el: '#app2',
  data: {
    labels : {lbl1:'Parent value 1'},
    values : {value: 'hello'},
  }
});

Here is jsFiddle: https://jsfiddle.net/davidhequet/ag0thqar/5/

Thank you, David

Upvotes: 0

Views: 1118

Answers (1)

Saurabh
Saurabh

Reputation: 73589

What I understand is, internalValue is not changing when value in parent is changing. You can set a watcher on value and whenever it changes, set internalValue, like following:

Vue.component('child2', {
  template: '#child2',
  ...
  ...
  ...
  created: function() {
    // We initially sync the internalValue with the value passed in by the parent
    this.internalValue = this.value;
    this.internallbl1 = this.lbl;
  },
  watch: {
    'internalValue': function() {
      // When the internal value changes, we $emit an event. Because this event is 
      // named 'input', v-model will automatically update the parent value
      this.$emit('input', this.internalValue);
    },    
     value: function(newVal) {
        this.internalValue = newVal
     }
  },
});

See working fiddle.

Upvotes: 1

Related Questions