Reputation: 6787
I have 2 vue variables. I want to set data for vue1 from vue2. What is the correct way to do it.
var vue1 = new Vue({
el: '#id1',
data: {
'name': 'Vue name'
},
methods: {
},
delimiters: ["[[", "]]"],
});
var vue2 = new Vue({
el: '#id2',
data: {
},
methods: {
func1:function (name) {
// Here i want to set vue1.name=name
vue1.name=name;
}
},
delimiters: ["[[", "]]"],
});
I have seen a function setData() but I dont know how to use it and if this is the correct scenario for that function.
Upvotes: 0
Views: 428
Reputation: 9200
I would add a method on the component itself for that purpose.
var vue1 = new Vue({
el: '#id1',
data: () => ({
name: 'Vue name'
}),
methods: {
changeName(name) {
this.name = name;
}
},
delimiters: ["[[", "]]"],
});
var vue2 = new Vue({
el: '#id2',
computed: {
input: {
get: () => vue1.name,
set: vue1.changeName
}
},
delimiters: ["[[", "]]"]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div>
<div id="id1">
<h2>[[$el.id]]</h2>
[[name]]
</div>
<div id="id2">
<h2>[[$el.id]]</h2>
<input v-model="input" />
</div>
</div>
Upvotes: 1
Reputation: 86
here is that way you can use data from one VUE instance to another Vue Instance . Using instance name with $data to catch the data , like app.$data.message . where i want to use first instance data to second app instance
var app = new Vue({
el: '#app',
data: {
message: 'first vue app message'
}
})
var app2 = new Vue({
el: '#app2',
data: {
message: app.$data.message
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
{{ message }}
</div>
<div id="app2">
{{ message }}
</div>
Upvotes: 0
Reputation: 3918
You can use a store pattern. For simple solution, you can use the following.
Store stores the shared values.
var store = {
state: {
name: null
},
setName: function(val) {
this.state.name = val;
},
};
How to access (or set) shared values from vue
.
var vue1 = new Vue({
el: '#id1',
data: {
sharedState: store.state,
otherValue: 'some value'
},
methods: {
set: function() {
store.setName('John Doe');
console.log(this.sharedState.name); // John Doe
}
},
});
Upvotes: 0