4
votes

I have some functionality that I'd like to share throughout my site. My site does have multiple Vue instances, and not just one single app instance entry point.

I've created my mixin like this:

var fooMixin = {
    data: {
        someProperty: null,
        someOtherProperty: "Foo"
    },
    methods{
       ...
    }
}

This mixin is then injected into my Vue instance like so:

new Vue({
    el: '#app',
    mixins: [fooMixin],
    data: {
        ...
    },
    methods: {
        ...
    }
})

Of course this works exactly as intended, but my issue is that I want to reuse this mixin within a component elsewhere. This causes issues.

Here's how it's injected into the component:

Vue.component('bar', {
    props: ['someProp'],
    template: barTemplate,
    mixins: [fooMixin],
    data: function () {
        return {
            mySpecialProperty: null
        }
    },
    methods: {
        ...
    }
})

As you can imagine, the mixin cannot be merged with the data property of the components. Since this is a component, the data property must return a function that return the object. This is not how my mixin has been set up.

This is the error I'm given from Vue:

[Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions.

Can I create a mixin that is reusable across instances and components?

1
For anyone wondering if you can keep state changes across mixins as functions: "Mixins are a flexible way to distribute reusable functionalities for Vue components" Mixins are for functionality and the vuex store is for state.IcyIcicle

1 Answers

0
votes

Change your data property in mixin from object to function

var mixin = {
  data: function () {
    return {
      someProperty: null,
      someOtherProperty: 'foo'
    }
  }
}