0

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?

1

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.