Writing in the front
Vue provides mixins and extends configuration items that have been found useful in recent use. Please correct any mistakes and thank u for the efficient production tools.
Mix mixins and extends
Mixins takes an array of objects (which can be interpreted as multiple inheritance), and extends takes an object or function (which can be interpreted as a single inheritance).
Inheriting hook functions
const extend = {
created () {
console.log('extends created')
}
}
const mixin1 = {
created () {
console.log('mixin1 created')
}
}
const mixin2 = {
created () {
console.log('mixin2 created')}}export default {
extends: extend,
mixins: [mixin1, mixin2],
name: 'app'.created () {
console.log('created')}}Copy the code
Console output
extends created
mixin1 created
mixin2 created
created
Copy the code
- Conclusion: The parent classes inherited from mixins and extends are called first, and extends triggers a higher priority, compared to queues
- Push (extend, mixin1, Minxin2, its own hook function)
- After testing, the value inheritance rules for Watch are the same.
Inherit the methods
const extend = {
data () {
return {
name: 'extend name'
}
}
}
const mixin1 = {
data () {
return {
name: 'mixin1 name'
}
}
}
const mixin2 = {
data () {
return {
name: 'mixin2 name'
}
}
}
// name = 'name'
export default {
mixins: [mixin1, mixin2],
extends: extend,
name: 'app'.data () {
return {
name: 'name'}}}Copy the code
// Write only subclasses, name ='mixin2 name', extends has a high priority and is overwritten by mixinsexport default {
mixins: [mixin1, mixin2],
extends: extend,
name: 'app'
}
Copy the code
// Write only subclasses, name ='mixin1 name'Mixins inheritance overrides the previous oneexport default {
mixins: [mixin2, mixin1],
extends: extend,
name: 'app'
}
Copy the code
- Conclusion: The subclass declares again that the variables in data will be overridden, and the subclass will prevail.
- If the subclass is not declared, the variables in data will take the last inherited parent class.
- When tested, the value inheritance rules for properties in props, methods in Methods, and computed are the same.
Write in the back
You can think of mixins and extend as the C (controller) layer of MVC. You can see that the generic member variables (including attributes and methods) are abstracted into a parent class, which is provided to subclasses for inheritance. This allows subclasses to have some generic member variables, but subclasses can also override the parent class’s member variables. This whole programming idea is very object-oriented, which is inheritance.
- Extends is also very common for inheriting existing components. See our previous article on Table configurability based on Element-UI to extend elder-UI’s el-table-column component.