The mixing mechanism of mixin in vue - new parent component

1. Understanding of mixins (mixing)
Vue provides a mixing mechanism - mixins, which is used to achieve the reuse of component content more efficiently. At first I thought it was no different from components. . It was later found to be wrong. Let's take a look at the difference between mixins and the introduction of components under normal circumstances?
After the component is referenced, it is equivalent to opening up a separate space in the parent component to perform corresponding operations according to the value of the parent component's props. In essence, the two are still distinct and relatively independent.
Mixins, after the introduction of the component, merges the content inside the component such as data and other methods, method and other attributes with the corresponding content of the parent component. It is equivalent to expanding the various property methods of the parent component after the introduction.
Simple component reference:
parent component + child component >>> parent component + child component
mixins:
parent component + child component >>> new parent component

It is worth noting that when using mixins, the parent component and the child component have various property methods in the child component at the same time, but this does not mean that they share and process these variables at the same time. any communication will take place. When I first saw mixins, naively, I seemed to see a downward data sharing scheme similar to vuex, and I was very excited. But after carefully studying the official api and some technical blogs, I found myself. . . Innocent.

For specific usage and content merging strategies, please refer to the official API and other technical posts
https://cn.vuejs.org/v2/guide/mixins.html
http://www.deboy.cn/Vue-mixins-advance-tips. html

Second, the use of mixins
1. Create a js file in the assets folder

// 创建一个需要混入的对象 
export const mixinTest1 = {
    created() {
        this.hello();
    },
    methods: {
        hello() {
            console.log('mixinTest1');
        }
    }
};

2. Use the mixin you just created in the component

import {mixinTest1} from './../assets/js/mixin';
export default {
    mixins:[mixinTest1],
    name: 'hello',
    data () {
        return {
            msg: 'Welcome to Your Vue.js App'
        }
    }
}
这样就可以直接调用到混入对象中的hello方法

3. If the method defined in the component is the same as the method/property in the mixed object, the priority in the component is higher than that in the mixed object (the method will be called multiple times)

4. An abstract method can be defined in the mixin object, and the component that uses the mixin must rewrite the method

...
methods: {
    handlePlaylist() {
        throw new Error('component must implement handlePlaylist method')
    }
}
...

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326694136&siteId=291194637