abagshaw
abagshaw

Reputation: 6582

VueJS Binding same variable to multiple of the same component

Let's say I have a basic page with VueJS as follows:

Vue.component('child', {
  template: '<p>{{message}}</p>',
  props: ["message"]
});

new Vue({
  el: '#theParent',
  data() {
    return {
      message: "It works!"
    }
  }
});
<script src="https://cdn.jsdelivr.net/vue/2.3.2/vue.min.js"></script>
<div id="theParent">
    <child v-bind:message="message"></child>
    <child v-bind:message="message"></child>
    <child v-bind:message="message"></child>
</div>

The message It works! shows up three times as expected, but if I remove v-bind:message="message" on my <child> components it doesn't work. As all my <child> components will require the value of message from the parent, is there a way to specify this once in the VueJS component declaration rather than each time in the HTML when adding a <child>?

Upvotes: 2

Views: 2765

Answers (1)

Bert
Bert

Reputation: 82439

One way to do this is to use a shared source of data.

console.clear()

const shared = {
  message: "It works!"
}

Vue.component('child', {
  template: '<p>{{shared.message}}</p>',
  data(){
    return {
      shared
    }
  }
});

new Vue({
  el: '#theParent',
  data:{
    shared
  }
});
<script src="https://cdn.jsdelivr.net/vue/2.3.2/vue.min.js"></script>
<div id="theParent">
    <child></child>
    <child></child>
    <child></child>
    <button @click="shared.message = 'new message'">Change message</button>
</div>

Here, any time the message changes, it's available everywhere. This is essentially a very slim data management solution. For a more complete state management solution you may want to look into Vuex, but you can go a very long way using a relatively simple shared data source and add in more complex solutions when you find you need them.

Upvotes: 2

Related Questions