vue3 mixins
时间: 2023-09-15 16:19:05 浏览: 86
Vue 3 mixins are a way to reuse code and functionality across multiple components in a Vue 3 application. Mixins allow you to define a set of options or methods that can be merged into a component's options during initialization.
To create a mixin in Vue 3, you can define a plain JavaScript object and export it as a module. This object can contain any options or methods that you want to reuse across components. For example:
```
// myMixin.js
export default {
data() {
return {
message: 'Hello from myMixin!'
}
},
methods: {
greet() {
console.log(this.message)
}
}
}
```
Then, in your component, you can use the `mixins` option to add the mixin to the component's options:
```
import myMixin from './myMixin'
export default {
mixins: [myMixin],
mounted() {
this.greet() // logs 'Hello from myMixin!'
}
}
```
When the component is initialized, the options from the mixin will be merged into the component's options. Any conflicting options will be overwritten by the mixin's options.
Note that mixins can also be chained together, so you can define multiple mixins and apply them to a component in the order you want them to be merged. However, be careful not to create naming conflicts or duplicate functionality when using multiple mixins.
阅读全文