If you find that the logic of several components is almost similar when writing a vue component, then you can use vue's mixin (mixin) to extract the similar logic and encapsulate it into js , and then introduced and used in each component.
mixin is used to solve the problem of logical reuse of vue components. Today we are going to learn Vue’s mixin.
mixin is mainly for vue’s js logic reuse, so it is generally a js file.
Let’s take a look at its usage first
// name.js export default { data () { return { name: 'mixin的name', obj: {name:'mixin', value:'mixin'} } }, methods: { getName () { console.log('我是mixin,name:', this.name) console.log('obj:', this.obj) } }, mounted () { console.log('我是mixin的mounted') this.getName() } }
Its usage is the same as that of the vue component. For example, hook functions, methods, data, etc.
Then use it in the component and introduce it through the mixins
option.
import name from './name.js' export default { mixins: [name], data () { } }
Then there will be a question, if the same hook function, method with the same name, and data with the same name are also defined in the component, whose one should prevail? Overwrite or merge?
Let’s take a look at the example
import name from './name.js' export default { mixins: [name], data () { name: '组件的name', obj: {name:'component'} }, methods: { getName () { console.log('我是组件,name:', this.name) console.log('obj:', this.obj) } }, mounted () { console.log('我是组件的mounted') this.getName() } }
The printed results are as follows:
##You can get it through the above results, The hook functions will be combined and executed.First execute the hook function of mixins and then execute the hook function of the component.
The data with the same name of data should be discussed on a case-by-case basis. If it is a basic type, the data of the mixin will be overwritten with the data of the same name of the component. But if it is an object, it willrecursively compare the key. If it is a key with the same name, it will be overwritten. If it is not the same name, it will be retained. The same goes for
methods, which will overwrite the mixin's method of the same name with the component's method. In addition to the above options, there are also options such ascomponents (components), and
directives (instructions), etc., which have the same logic. Those with the same name will be overwritten, ending with
Component is given priority.
vue video tutorial"
The above is the detailed content of Let's learn Vue's mixin together. For more information, please follow other related articles on the PHP Chinese website!