B
B
Bogdan2018-02-13 21:33:26
Vue.js
Bogdan, 2018-02-13 21:33:26

Pass variable from child component to parent?

Hello. And how correctly to transfer values ​​from child component to parent.
Here is an example, but maybe there is a better solution? Thanks
Example

Vue.component('app-some', {
  props: ['valueParent', 'idParent'],
  template: `
    <div>
      <input v-model='valueChild' @input='onInput' >
    </div>
  `,
  data(){
    return {
      valueChild: ''
    }
  },
  mounted() {
    this.valueChild = this.valueParent;
  },
  methods: {
    onInput( ){
      this.$emit( 'changeValue', this.idParent, this.valueChild );
    }
  }
});



new Vue({
  el: '#app',
  template: `
    <div>
      <div v-for='(item, index) in items'>
        <app-some :valueParent='item.value' :idParent='index' @changeValue='changeItems' ></app-some>
      </div>
      <pre> {{ items }}</pre>
    </div>`,
  data() {
    return {
      items: [ { value: '1' }, { value: 2 }]
    }
  },
  methods: {
    changeItems(index, newValue) {
      this.items[index].value = newValue;
    }
  }
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ramil, 2018-02-14
@bogdan_uman

You have the right direction. This one -way binding approach is exactly what Vue.js requires. In this case, you are always in control of the input and output parameters.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question