Output data from one instance of Vue.js to another

I have a pretty big page with a lot of stuff. Therefore, I have 2 Vue instances for 2 parts of the page. How can I bind data from one Vue instance to another?

This example should show what I'm trying to do. (it does not work that way)

<div class="app1">...</div> ... <div class="app2">{{app1.$data.msg}}</div> 

 var app1 = new Vue({ el: '.app1', data: {msg: "test"} }); var app2 = new Vue({ el: '.app2' }); 
+5
source share
2 answers

In advance, I know that this is not a question that you ask, but I do not know why you need two instances of Vue. Why not just associate Vue with the body and treat Vue instances as components. It may be difficult for you to do what you are trying to do, because it was not intended. Perhaps it was, I do not know. I put Vue on the body and I did not see a performance hit. Here is the JSBin .

HTML

 <div class="container"> <div id="app1"> <h1>{{ msg }}</h1> <input type="text" v-model="msg" class="form-control"/> </div> <div id="app2"> <h1>{{ msg }}</h1> <input type="text" v-model="msg" class="form-control"/> </div> </div> 

Javascript

 var VueComponent1 = Vue.extend({ template: '#app1', data: function(){ return { msg: "" } } }); var VueComponent2 = Vue.extend({ template: '#app2', data: function(){ return { msg: "" } } }); var app1 = Vue.component('app1', VueComponent1); var app2 = Vue.component('app2', VueComponent2); var app = new Vue({ el: 'body', data: { msg: 'Everybody loves Vue.' } }); 

If you're looking for a better way to split your code, you can check out this Vue with the Browserify example .

Laracasts has a free series on Vue, which was also pretty informative.

+5
source

I'm still looking for a better solution. The following looks a bit hacky, but it works.

You can use the view function to listen to the expression change and call the function. In this function, you can update the desired data of another Vue instance. In this example, we will do the following:

 var app1 = new Vue({ el: '.app1', data: {msg: 'test'}, watch: { 'msg': function() { app2.msg = this.msg; } } }); var app2 = new Vue({ el: '.app2', data: { msg: app1.$data.msg }, watch: { 'msg': function() { app1.msg = this.msg; } } }); 

You can see it at work this jsbin .

Moreover, I am wondering if you need to do this. If this were a real situation, there might be better ways to deal with this, avoiding this hacker solution.

+1
source

All Articles