Master Vue.js Mixins: Reuse Code and Simplify Component Logic
This article explains what Vue.js mixins are, how they merge component options, demonstrates their behavior with code examples, and shows practical use cases such as shared download logic to reduce redundancy across multiple components.
Preface
In everyday development you may encounter two or more similar components that share some functions but also have differences. Splitting them into separate components can lead to duplicated code, while using a single component with many props becomes confusing.
Vue's official documentation introduces mixins as a flexible way to solve this problem. This article introduces mixins and shows how to use them in Vue.
Basics: Understanding Mixins
According to the official docs, a mixin provides a flexible way to distribute reusable functionality in Vue components. A mixin object can contain any component options, including lifecycle hooks, data, methods, etc. When a component uses a mixin, all options from the mixin are merged into the component's own options.
// Define a mixin object
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// Define a component that uses the mixin
var Component = Vue.extend({
mixins: [myMixin] // include the mixin
})
var component = new Component() // => "hello from mixin!"The code above first defines a mixin with a created hook and a hello method. Then a component is created that includes this mixin, so the hook runs and logs the message.
When a component uses a mixin, options are merged. For lifecycle hooks with the same name, they become an array and the mixin's hook runs first. For data, the component's values take precedence. For objects like methods, keys that conflict are overridden by the component.
var mixin = {
data: function () {
return {
message: 'hello',
mixinData: 'abc'
}
},
created: function () {
console.log('hello,begain use mixin')
},
methods: {
foo: function () { console.log('foo') },
conflicting: function () { console.log('from mixin') }
}
}
var vm = new Vue({
mixins: [mixin],
data: function () {
return { message: 'goodbye', barData: 'def' }
},
created: function () {
console.log(this.$data) // => { message: "goodbye", mixinData: "abc", barData: "def" }
},
methods: {
bar: function () { console.log('bar') },
conflicting: function () { console.log('from self') }
}
})
vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"In this example the component's created hook runs after the mixin's, and the component's data values override the mixin's. The component's own conflicting method also overrides the mixin's.
Mixin Application
Before using mixins, understand two key characteristics: (1) a mixin merges its options into the component, creating a new component definition; (2) data and methods from a mixin are not shared between components that use the same mixin.
Therefore mixins should not be used for component-to-component communication.
Mixins are ideal when multiple components need the same functionality. For example, many pages may have a download button that requires permission checks. Instead of duplicating the logic, a mixin can encapsulate the download behavior.
Step 1: Create download.js defining the mixin with a default download URL and logic.
export default {
data () {
return {
downloadUrl: 'http://downloadUrl/default/'
}
},
methods: {
downloadClick: function () {
console.log('下载链接是', this.downloadUrl)
// download business logic
}
}
}Step 2: Use the mixin in a component that can use the default logic.
<template>
<div id="default">
<button @click="downloadClick">下载文件</button>
</div>
</template>
<script>
import downloadButton from './download'
export default {
name: 'default',
mixins: [downloadButton]
}
</script>The component now calls downloadClick and logs the default URL.
Step 3: For a component that needs a custom URL, still include the mixin but override downloadUrl.
<template>
<div id="myself">
<button @click="downloadClick">下载文件</button>
</div>
</template>
<script>
import downloadButton from './download'
export default {
name: 'myself',
mixins: [downloadButton],
data () {
return {
downloadUrl: 'http://downloadUrl/myself/'
}
}
}
</script>When the button is clicked, the component's own downloadUrl is used, printing the custom URL.
These examples demonstrate simple, practical applications of mixins to reduce code duplication, such as shared download logic or modal open/close handling.
Conclusion
This article discussed Vue mixins, their option merging behavior, how to use them, and practical scenarios. Understanding mixin characteristics helps you decide when to apply them effectively in frontend development.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
