To use Vue.js mixins to share code between components, you can follow these steps:
Create a mixin object with the code you want to share. This object can contain data, computed properties, methods, lifecycle hooks, and other options that a component can have. For example:
const myMixin = {
data() {
return {
message: "Hello from mixin"
}
},
methods: {
showMessage() {
console.log(this.message);
}
}
}
Apply the mixin to a component by using the mixins
option. You can apply multiple mixins if needed. For example:
Vue.component('my-component', {
mixins: [myMixin],
// ...
});
Use the code from the mixin in the component as if it's defined directly in the component. For example:
Vue.component('my-component', {
mixins: [myMixin],
template: `<div>
<p>{{ message }}</p>
<button @click="showMessage()">Show Message</button>
</div>`
});
In the above example, the component will have access to the message
data and the showMessage
method defined in the mixin.
You can override or extend the properties and methods from the mixin in the component by simply defining those properties or methods again in the component. The component's property or method will override that of the mixin. For example:
Vue.component('my-component', {
mixins: [myMixin],
data() {
return {
message: "Hello from component"
}
}
});
In this case, the message
data from the component will override the message
data from the mixin.
By using mixins, you can easily share common code among multiple components without the need for duplicating the code or creating a parent component.