How to use mixins in Vue.js?

Mixins allow you to reuse component options. For example, to share methods or lifecycle hooks among multiple components:

// myMixin.js
export const myMixin = {
  data() {
    return {
      sharedData: 'This data is shared among components'
    };
  },
  methods: {
    sharedMethod() {
      console.log('This method is shared');
    }
  }
};

To use the mixin in a component:

// MyComponent.vue
import { myMixin } from './myMixin';

export default {
  mixins: [myMixin],
  mounted() {
    console.log(this.sharedData);
    this.sharedMethod();
  }
};

 

Post your Answer