[Vuejs]-Vue.js 2.x: Mixin cannot be referenced from components?

1👍

You can add global mixin

Vue.mixin({
    methods: {
        say: function () {
            return "Hi";
        }
    }
})

or add mixin to component

vm = new MyVue({
    el: "#parent",
    components: {
        child: {
            template: "<div>{{say() }}</div>",
            mixins: [mixin]
        }
    }
});

4👍

If you want to use share a mixin between multiple components, but not between all components, you can do that without making it global. Here’s how:

in /src/mixins/mixin.js

export default {
    created() {
      console.log("created a mixin!")
    },
    methods: {} //any methods you want go here
}

in your .vue component (ex: /src/components/Component.vue)

<script>
  import Mixin from '../mixins/mixin.js'
  export default {
     mixins: [Mixin],
....

The most important thing to note is that I used export default in both my .js file AND my .vue component.

Leave a comment