2

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/

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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'
    }
  }
});

JSFiddle

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.