Meet Mixins
At present, we use a componentized development method to develop applications, but there are some common code logics between different components, and we hope to extract the same code logic at this time.
Mixin is supported in both vue2 and vue3. Mixin provides a very flexible way to distribute reusable functions in Vue components. A Mixin object can contain any component options. When a component uses a Mixin object, all The options of the Mixin object will be mixed into the options of the component itself.
Officially defined Mixin
Mixins provide a very flexible way to distribute reusable functionality in Vue components. A mixin object can contain arbitrary component options. When a component uses a mixin object, all the mixin object's options will be "mixed" into the component's own options.
How to use Mixin in the project
Create a mixins folder under the src folder
Under the demomixins.js file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Under the Home.vue file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
Although we have not defined the msg variable, the message calculation property, and the foo method in home.vue, they can be displayed on the page.
Mixin Merging Rules
If the options in the Mixin object conflict with the options in the component object, how will Vue operate?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
Above we can see that:
The msg attribute in the mixed-in object conflicts with the msg attribute of the component, and the value of the component takes precedence. Attributes that are not in the component will take effect when mixed into the object.
The hook functions with the same name will be merged into an array and will be called, and the mixed-in function will be called first
Options whose values are objects, such as methods, computed, etc., will be merged into a new object. If the key name conflicts, the value of the component will take precedence
Global Mixin
If some options in the component are required by all components, then we can use the global mixin at this time. Once registered, the global mixin options will affect every component
1 2 3 4 5 6 7 8 |
|
The official definition extends
Allows a component to extend to another component and inherit options from that component.
extends类似于mixin,相当于继承,但是只是继承options Api中的内容,不继承template模板。
项目中使用extends
在components创建一个组件my.vue
1 2 3 4 5 6 7 8 9 |
|
在Home.vue文件下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
在开发中extends用的非常少,在Vue2中比较推荐大家使用Mixin,而在Vue3中推荐使用Composition API。