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.
<code>// 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!"
</code>The code above first defines a mixin with a
createdhook and a
hellomethod. 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.
<code>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"
</code>In this example the component's
createdhook runs after the mixin's, and the component's
datavalues override the mixin's. The component's own
conflictingmethod 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.jsdefining the mixin with a default download URL and logic.
<code>export default {
data () {
return {
downloadUrl: 'http://downloadUrl/default/'
}
},
methods: {
downloadClick: function () {
console.log('下载链接是', this.downloadUrl)
// download business logic
}
}
}
</code>Step 2: Use the mixin in a component that can use the default logic.
<code><template>
<div id="default">
<button @click="downloadClick">下载文件</button>
</div>
</template>
<script>
import downloadButton from './download'
export default {
name: 'default',
mixins: [downloadButton]
}
</script>
</code>The component now calls
downloadClickand logs the default URL.
Step 3: For a component that needs a custom URL, still include the mixin but override
downloadUrl.
<code><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>
</code>When the button is clicked, the component's own
downloadUrlis 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.
37 Mobile Game Tech Team
37 Mobile Game Tech Team
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.