目录
1、在组件中使用
混入 (mixin) 提供了一种非常灵活的方式,来分发 vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。
<template>
<div class="event_style">
<h2>基础</h2>
<div class="inner_children">
<span>{{ message }}</span>
</div>
</div>
</template>
<script>
var myMixin = {
data() {
return {
message: "",
};
},
created: function () {
console.log("created:add mixin");
this.message = "created:add mixin";
this.hello();
},
methods: {
hello: function () {
console.log("hello from mixin!");
},
},
};
// 定义一个使用混入对象的组件
export default {
name: "mixin-basic",
mixins: [myMixin],
};
</script>
2、选项合并
当组件和混入对象含有同名选项时,这些选项将以恰当的方式进行“合并”。
比如,数据对象在内部会进行递归合并,并在发生冲突时以组件数据优先。
<template>
<div class="event_style">
<h2>选项合并</h2>
<div class="inner_children">
<span>{{ message }}</span>
<span>{{ message1 }}</span>
</div>
</div>
</template>
<script>
var myMixin = {
data() {
return {
message: "mixin:mixin",
message1: "mixin:mixin-1",
};
},
created: function () {
this.hello();
},
methods: {
hello: function () {
console.log("mixin:hello from mixin!");
},
},
};
// 定义一个使用混入对象的组件
export default {
name: "mixin-merge",
mixins: [myMixin],
data() {
return {
message: "组件:hello",
};
},
created: function () {
this.hello();
},
methods: {
hello: function () {
console.log("组件:hello world!");
},
},
};
</script>
<style scoped>
.event_style {
padding-left: 50px;
padding-right: 50px;
}
.inner_children {
display: flex;
flex-direction: column;
height: 150px;
border: 1px solid #333;
padding: 6px;
}
.inner_children span {
font-size: 20px;
}
</style>
页面呈现的效果
由上图可以看出,混入的数据和方法和组件定义的有冲突时,以组件的优先,当组价中未定义时,才会进行合并,显示混入定义的效果
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注华域联盟的更多内容!
您可能感兴趣的文章:
- 详解Vue.js Mixins 混入使用
- Vue初始化中的选项合并之initInternalComponent详解
- vue使用混入定义全局变量、函数、筛选器的实例代码
- 使用vue中的混入mixin优化表单验证插件问题
声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。


评论(0)