Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第73题:什么是mixins? #73

Open
noxussj opened this issue Jun 18, 2020 · 0 comments
Open

第73题:什么是mixins? #73

noxussj opened this issue Jun 18, 2020 · 0 comments
Labels

Comments

@noxussj
Copy link
Owner

noxussj commented Jun 18, 2020

混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项

栗子

子组件A

<template>
    <!-- 子组件A -->
    <div class="views__home__sub-model-a"></div>
</template>


<script>
import mixin from './mixin.js';

export default {
    mixins: [mixin],
    mounted() {
        console.log('sub-model-a', 'mounted');
    }
};
</script>

子组件B

<template>
    <!-- 子组件B -->
    <div class="views__home__sub-model-b"></div>
</template>


<script>
import mixin from './mixin.js';

export default {
    mixins: [mixin],
    mounted() {
        console.log('sub-model-b', 'mounted');
    }
};
</script>

mixin.js

export default {
    mounted() {
        console.log('mixin', 'mounted');
    }
};

打印结果
image

可以看见生命周期钩子一般都是先执行mixin里面的方法,然后才到组件的方法

那么问题就来了,万一mixin和组件的选项冲突了怎么办呢?

选项合并

当组件和混入对象含有同名选项时,这些选项将以恰当的方式进行“合并”。

比如,数据对象在内部会进行递归合并,并在发生冲突时以组件数据优先

这边就只列举data选项

子组件A

<template>
    <!-- 子组件A -->
    <div class="views__home__sub-model-a"></div>
</template>


<script>
import mixin from './mixin.js';

export default {
    mixins: [mixin],
    data() {
        return {
            student: {
                age: 20
            }
        };
    },
    mounted() {
        console.log('sub-model-a', this.student);
    }
};
</script>

mixin.js

export default {
    data() {
        return {
            student: {
                name: 'xiaoming',
                age: 10
            }
        };
    },
    mounted() {
        console.log('mixin', this.student);
    }
};

打印结果
image

可以看出来student对象进行了合并,age是冲突的并且以组件的为准

@noxussj noxussj added the Vue label Jun 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant