Application of common method for mixin encapsulation
Public method for creating a new file under src: mixin/
const baseMixin = { data() { return { title: 'This is a public title' } }, methods: { onClick() { ('I was clicked') } } } export default baseMixin;
Then you can call it in the component that needs to be called: src/view/
<template> <div class="baseMixin"> <h1> This is the call reuse title: {{title}} // Rendering: This is a common title </h1> <h2> <button @click="onClick"> // Print: I was clicked This is a reuse method </button> </h2> </div> </template>
<script> import baseMixin from '@/mixin/baseMixin' export default { mixins: [baseMixin], setup() { let text = 'This is a method record of the vue3 version of mixin' return { text } } } </script>
If you need to use the mixin package directly globally, you can declare it in it
import { createApp } from 'vue' import App from './' import baseMixin from './mixin/baseMixin' createApp(App).mixin(baseMixin).mount('#app')
vue3 basics-mixin usage
Mixin Features
- Component data priority higher than mixin data priority
- Component methods priority: methods prioritize higher than mixin
- Declare the periodic function, first execute the mixin, and then execute the component
- Local mixin, need to be registered in the component mixins: [myMixin]
- Global mixin does not need to be registered in the component and is automatically injected.
Define local mixin
Similar to defining local components, it supports data, methods and declares periodic functions.
const myMixin = { data() { return { msg: 'hello vue3' } }, created() { ('mixin created'); }, methods: { handleClick() { ('mixin', ); } } }
Define global mixin (not recommended)
// Global mixin does not need to be registered in the component and is automatically injected.({ mounted() { ('This is a global mixin'); } })
Adjust the priority of attributes in mixin
const myMixin = { msg: 'hello mixin ~' } // All options registered by the $options component will be in $optionsconst app = ({ mixins: [myMixin], msg: 'hello app ~', template: ` <div> {{ $ }} </div>`, }) // ** Adjust the priority of properties in the mixin (such as: msg) to make the mixin priority of the advanced components = (mixinValue, appValue) => { return mixinValue || appValue; }
The above is personal experience. I hope you can give you a reference and I hope you can support me more.