CrazySynthax
CrazySynthax

Reputation: 14988

vue.js two way data-binding between components

Please take a look at this not-working pseudo code:

Vue.component('child', {
    props: [],
    template: '<div><input v-model="text"></div>',
    data: function() {
      return {child-text: ""}     
    } 
})

Vue.component('parent', {
    template: '<h1> {{text}} </h1>'
    data: function() {
      return {parent-text: ""}
    }
})

What is the most elegant way to fix this code that whenever the user changes the content of input box in child component, then the variable child-text in child component and the variable parent-text in parent component will change automatically? I also want that if the variable child-text and/or parent-text change then the content of input box will change respectively?

Upvotes: 0

Views: 627

Answers (1)

Matthias S
Matthias S

Reputation: 3553

I solved this with my own little data store, its a very simple approach but works good enough for me without the necessity to dive into Vuex.

First, I create my data store somewhere before initializing anything else.

window.globalData = new Vue({
    data: {
        $store: {}
    },
});

After that, I add a global Mixin that allows to get and set data to the global storage.

Vue.mixin({
    computed: {
        $store: {
            get: function () { return window.globalData.$data.$store },
            set: function (newData) { window.globalData.$data.$store = newData; }
        }
    }
});

Then, every component can access the data storage by this.$store. You can check a working example here:

https://codesandbox.io/s/62wvro7083

Edit Vue Template

Upvotes: 1

Related Questions