Vue混入使用和選項(xiàng)合并詳解
1、在組件中使用
混入 (mixin) 提供了一種非常靈活的方式,來(lái)分發(fā) Vue 組件中的可復(fù)用功能。一個(gè)混入對(duì)象可以包含任意組件選項(xiàng)。當(dāng)組件使用混入對(duì)象時(shí),所有混入對(duì)象的選項(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!"); }, }, }; // 定義一個(gè)使用混入對(duì)象的組件 export default { name: "mixin-basic", mixins: [myMixin], }; </script>
2、選項(xiàng)合并
當(dāng)組件和混入對(duì)象含有同名選項(xiàng)時(shí),這些選項(xiàng)將以恰當(dāng)?shù)姆绞竭M(jìn)行“合并”。
比如,數(shù)據(jù)對(duì)象在內(nèi)部會(huì)進(jìn)行遞歸合并,并在發(fā)生沖突時(shí)以組件數(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!"); }, }, }; // 定義一個(gè)使用混入對(duì)象的組件 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>
頁(yè)面呈現(xiàn)的效果
由上圖可以看出,混入的數(shù)據(jù)和方法和組件定義的有沖突時(shí),以組件的優(yōu)先,當(dāng)組價(jià)中未定義時(shí),才會(huì)進(jìn)行合并,顯示混入定義的效果
總結(jié)
本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
vue實(shí)現(xiàn)圖片滑動(dòng)驗(yàn)證功能
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)圖片滑動(dòng)驗(yàn)證功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-09-09詳解本地Vue項(xiàng)目請(qǐng)求本地Node.js服務(wù)器的配置方法
本文只針對(duì)自己需要本地模擬接口于是搭建一個(gè)本地node服務(wù)器供自己測(cè)試使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-03-03使用Vue完成一個(gè)簡(jiǎn)單的todolist的方法
本篇文章主要介紹了使用Vue完成一個(gè)簡(jiǎn)單的todolist的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-12-12