Vue.js Mixins: Sharing Component Logic

Mixins let you share logic between Vue components. They’re like traits or multiple inheritance for components.

Creating a Mixin

// mixins/formMixin.js
export const formMixin = {
  data() {
    return {
      isSubmitting: false,
      errors: {}
    };
  },
  methods: {
    async submitForm(apiCall) {
      this.isSubmitting = true;
      this.errors = {};
      try {
        await apiCall();
      } catch (e) {
        this.errors = e.response?.data?.errors || {};
      } finally {
        this.isSubmitting = false;
      }
    }
  }
};

Using a Mixin

<script>
import { formMixin } from '@/mixins/formMixin';

export default {
  mixins: [formMixin],
  methods: {
    save() {
      this.submitForm(() => api.saveUser(this.user));
    }
  }
};
</script>

Caution

Mixins can create implicit dependencies and naming conflicts. In Vue 3, the Composition API is preferred for code reuse. But for Vue 2, mixins remain a valid approach.


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.