Use variables from other Vue instances and cross reference them

I have 2 different parts of the website

First: is it ok to use one instance in another especially with v-model, is this have any disadvantages.

Second: Is there any way I can cross reference each other, like footer in aside even though one is declared before the other. I get an error with this code. "footer is undefined"

My JS:

var aside = new Vue({
    "el":"aside",
    data:{
        name:"Peylan"
    }
});
var footer= new Vue({
    "el":"footer",
    data:{
        companyname:"Company Inc"
    }
});

My HTML

<aside><h3 v-bind="footer.companyname"></h3></aside>
<footer>
    <input type="text" v-model="aside.name">
</footer>

Answers:

Answer

Standard way of handling what you want is using a shared Vuex store.

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>

<aside><h3 v-text="footer.companyname"></h3></aside>
<footer>
    <input type="text" v-model="aside.name">
</footer>

<script>
const store = new Vuex.Store({
    strict: false,
    state: {
        aside: {
            name:"Peylan"
        },
        footer: {
            companyname:"Company Inc"
        }
    }
});
var aside = new Vue({
    store,
    "el":"aside",
    data:{},
    computed: {
        ...Vuex.mapState(['aside', 'footer'])
    }
});
var footer= new Vue({
    store,
    "el":"footer",
    data:{},
    computed: {
        ...Vuex.mapState(['aside', 'footer'])
    }
});
</script>

The demo above is a very simplified way of using it. For optimal usage (like with getters, actions and mutations) consider Vuex's official docs.


Or you can use a computed property on both, like below.

This creates a bit of a chicken and egg issue, that's why you need to use .$mount() in this case.

<script src="https://unpkg.com/vue"></script>

<aside><h3 v-text="footer.companyname"></h3>
</aside>
<footer>
    <input type="text" v-model="aside.name">
</footer>

<script>
var aside = new Vue({
    data:{
        name:"Peylan"
    },
    computed: {
        footer() { return footer; }
    }
});
var footer = new Vue({
    data:{
        companyname:"Company Inc"
    },
    computed: {
        aside() { return aside; }
    }
});
aside.$mount("aside");
footer.$mount("footer");
</script>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.