Roman Panaget
Roman Panaget

Reputation: 2428

VueJs - Binding bidirectionnaly parent and child data

I'm pretty new in Vuejs. I read the documentation and a few articles on the internet but I still have a question about components binds.

I read that you can pass data from the parent to the child easily with the props and that you can call the parent from the child with a sort of callback with emit.

I was wondering if there is a way to bind directly the props from both components. One change of the child's data would induce a change in the parents one, and vice-versa, without having to manage callback functions.

Upvotes: 0

Views: 46

Answers (2)

user115014
user115014

Reputation: 922

What you might want to consider is Vuex which is used to manage state.

As their homepage says: "It serves as a centralised store [of state] for all the components in an application..."

Any number of components can watch for changes to the state and a component can 'react' whenever there are any changes to that state — meaning that a component automatically changes according to the state.

The most important thing to remember is that state is immutable, it can be copied, changed and a new version published but there is only ever one source of truth - this helps in managing the state of your application because there is only ever one source of truth for the state of the application.

This might be a good place to get some info: freecodecamp article

Hope that helps.

Upvotes: 1

Riddhi
Riddhi

Reputation: 2244

Template

<div id="app">

  <h1>2-way props</h1>
  <p>Test of mechanics required for independent 2-way props in Vue 2</p>
  <p>Updated example using a mixin.</p>

  <section>
    <label>1. App:</label>
    <pre>data: {{ $data }} </pre>
    <ui-input :value.sync="value"></ui-input>
  </section>

</div>

<template id="input">
  <section>
    <label>2. {{ name }}:</label>
    <input v-model="val" @change="onInput">
    <pre>data: {{ $data }}</pre>
  </section>
</template>

Script

const Field = {

  props:['value'],

  data () {
    return { val:this.value }
  },

  watch: {
    value (value) {
        this.val = value
    }
  },

  methods: {
    onInput() {
        this.$emit('update:value', this.val)
    }
  },

}

Vue.component('ui-input', {

    template:'#input',

  mixins: [Field],

  data () {
    return { name: 'Component' }
    },

})


new Vue({
    data () {
    return {
      value: 'foo'
    }
  }
}).$mount('#app')

Please refer the fiddle. https://jsfiddle.net/RiddhiParekh/d60p75Lr/

Upvotes: 0

Related Questions