Vue混入使用和選項(xiàng)合并詳解
1、在組件中使用
混入 (mixin) 提供了一種非常靈活的方式,來分發(fā) Vue 組件中的可復(fù)用功能。一個混入對象可以包含任意組件選項(xiàng)。當(dāng)組件使用混入對象時,所有混入對象的選項(xiàng)將被“混合”進(jìn)入該組件本身的選項(xiàng)。
<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、選項(xiàng)合并
當(dāng)組件和混入對象含有同名選項(xiàng)時,這些選項(xiàng)將以恰當(dāng)?shù)姆绞竭M(jìn)行“合并”。
比如,數(shù)據(jù)對象在內(nèi)部會進(jìn)行遞歸合并,并在發(fā)生沖突時以組件數(shù)據(jù)優(yōu)先。
<template>
<div class="event_style">
<h2>選項(xiàng)合并</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)文章
npm無法加載文件:因?yàn)樵诖讼到y(tǒng)上禁止運(yùn)行腳本的解決辦法
這篇文章主要介紹了npm無法加載文件:因?yàn)樵诖讼到y(tǒng)上禁止運(yùn)行腳本問題的解決辦法,文中通過代碼以及圖文介紹的非常詳細(xì),需要的朋友可以參考下2025-01-01
vue2.0使用swiper組件實(shí)現(xiàn)輪播效果
這篇文章主要為大家詳細(xì)介紹了vue2.0使用swiper組件實(shí)現(xiàn)輪播效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11
基于VUE實(shí)現(xiàn)簡單的學(xué)生信息管理系統(tǒng)
這篇文章主要介紹了VUE實(shí)現(xiàn)一個簡單的學(xué)生信息管理系統(tǒng),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01
vue實(shí)現(xiàn)簡單數(shù)據(jù)雙向綁定
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)簡單數(shù)據(jù)雙向綁定,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-04-04

