Vue 3 Mixin Reuse Component Options

By using the mixins option, you can apply a mixin object to one or more components, merging the options from the mixin object into the component's options.
The following example demonstrates how to use the mixin option in Vue 3:

// Define a mixin object
const myMixin = {
  created() {
    console.log('Mixin created');
  },
  methods: {
    mixinMethod() {
      // Log when the mixin method is called
      console.log('Mixin method');
    }
  }
};

export default {
  name: 'MyComponent',
  mixins: [myMixin],
  
  created() {
    console.log('Component created');
  },
  methods: {
    componentMethod() {
      // Log when the component method is called
      console.log('Component method');
    }
  }
}

In the code above, we first define a mixin object named myMixin. This mixin object contains a lifecycle hook (created) and a custom method (mixinMethod).
Then, within the component's options object, we use the mixins option to merge myMixin into the component. As a result, the options from the mixin object are merged with those of the component. In this example, the created lifecycle hook and mixinMethod method will be integrated into the component.
Finally, within the component itself, we define another created lifecycle hook and a custom method (componentMethod).

When the component is created, Vue 3 calls the hooks and methods in the following order:

  1. The created hook function from the mixin object is called first.
  2. The created hook function of the component itself is then called.
  3. When mixinMethod is invoked within the component, the method defined in the mixin object (myMixin) will be executed.
  4. When componentMethod is invoked within the component, the method defined directly on the component itself will be executed.