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.