javascript - VueJS Binding same variable to multiple of the same component -


let's have basic page vuejs 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 3 times expected, if remove v-bind:message="message" on <child> components doesn't work. <child> components require value of message parent, there way specify once in vuejs component declaration rather each time in html when adding <child>?

one way use 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, time message changes, it's available everywhere. very slim data management solution. more complete state management solution may want vuex, can go long way using relatively simple shared data source , add in more complex solutions when find need them.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -