We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
混入 (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'); } };
打印结果
可以看见生命周期钩子一般都是先执行mixin里面的方法,然后才到组件的方法
那么问题就来了,万一mixin和组件的选项冲突了怎么办呢?
当组件和混入对象含有同名选项时,这些选项将以恰当的方式进行“合并”。
比如,数据对象在内部会进行递归合并,并在发生冲突时以组件数据优先
这边就只列举data选项
<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>
export default { data() { return { student: { name: 'xiaoming', age: 10 } }; }, mounted() { console.log('mixin', this.student); } };
可以看出来student对象进行了合并,age是冲突的并且以组件的为准
The text was updated successfully, but these errors were encountered:
No branches or pull requests
混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项
栗子
子组件A
子组件B
mixin.js
打印结果
可以看见生命周期钩子一般都是先执行mixin里面的方法,然后才到组件的方法
那么问题就来了,万一mixin和组件的选项冲突了怎么办呢?
选项合并
当组件和混入对象含有同名选项时,这些选项将以恰当的方式进行“合并”。
比如,数据对象在内部会进行递归合并,并在发生冲突时以组件数据优先
这边就只列举data选项
子组件A
mixin.js
打印结果
可以看出来student对象进行了合并,age是冲突的并且以组件的为准
The text was updated successfully, but these errors were encountered: