Vue混入使用和選項合并詳解
1、在組件中使用
混入 (mixin) 提供了一種非常靈活的方式,來分發(fā) Vue 組件中的可復(fù)用功能。一個混入對象可以包含任意組件選項。當(dāng)組件使用混入對象時,所有混入對象的選項將被“混合”進(jìn)入該組件本身的選項。
<template>
<div class="event_style">
<h2>基礎(chǔ)</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、選項合并
當(dāng)組件和混入對象含有同名選項時,這些選項將以恰當(dāng)?shù)姆绞竭M(jìn)行“合并”。
比如,數(shù)據(jù)對象在內(nèi)部會進(jìn)行遞歸合并,并在發(fā)生沖突時以組件數(shù)據(jù)優(yōu)先。
<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>
頁面呈現(xiàn)的效果

由上圖可以看出,混入的數(shù)據(jù)和方法和組件定義的有沖突時,以組件的優(yōu)先,當(dāng)組價中未定義時,才會進(jìn)行合并,顯示混入定義的效果
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
詳解本地Vue項目請求本地Node.js服務(wù)器的配置方法
本文只針對自己需要本地模擬接口于是搭建一個本地node服務(wù)器供自己測試使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-03-03

