Reputation: 700
I'm using a mixin to add and override vue data. I am able to add new data, but I cannot seem to override existing data. Here is the simple code:
var mixin = {
data: function() {
return {
foo: 'boo',
test: 'blah'
}
}
}
var vm = new Vue({
el: '#vue-instance',
mixins: [mixin],
data: function() {
return {
foo: 'bar'
}
}
});
When I run it, 'test' equals 'blah' properly, but 'foo' still equals 'bar'. Is there anyway to have a mixin override existing vue data in addition to adding new data?
Here is a fiddle:
https://jsfiddle.net/8v9sfxok/
Upvotes: 2
Views: 5746
Reputation: 14697
From the mixins documentations:
Options that expect object values ... will be merged into the same object. The component’s options will take priority when there are conflicting keys in these objects
(emphasis mine).
If you want a different merge strategy, you can define one.
Upvotes: 2
Reputation: 700
As some have mentioned, mixins cannot override existing data. For this I had to take my original component and make it a "base" component. Then use the "extends" option in another component to override existing data.
Upvotes: 0
Reputation: 33873
One way around this is to create a method in your mixin and invoke that from your template:
html:
<div id="vue-instance">
<p>
{{getFoo()}}
</p>
<p>
{{test}}
</p>
</div>
JavaScript:
var mixin = {
data: function() {
return {
foo: 'baz',
test: 'blah'
}
},
methods: {
getFoo: function () {
return 'baz';
}
}
}
var vm = new Vue({
el: '#vue-instance',
mixins: [mixin],
data: function() {
return {
foo: 'bar'
}
}
});
Upvotes: 0