4

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. Commented Nov 10, 2021 at 17:41

1 Answer 1

0

Change your data property in mixin from object to function

var mixin = {
  data: function () {
    return {
      someProperty: null,
      someOtherProperty: 'foo'
    }
  }
}
Sign up to request clarification or add additional context in comments.

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.