想要封裝好一個自己的vue組件,一定要熟練掌握這三個技能
父組件 —> 子組件傳值(props)
子組件 —> 父組件傳值($emit)
以及插槽(slot)
對于一個獨立的組件來說
props是用來為組件內部注入核心的內容;
$emit用來使這個獨立的組件通過一些邏輯來融入其他組件中。
舉個具體點的例子,假如你要做一輛車,車輪是要封裝的一個獨立組件,props指的就是根據整個車的外形你可以給輪子設置一些你想要的且符合車風格的花紋,圖案等;
而$emit的作用則是讓這些輪子能夠和整輛車完美契合的運作起來。差不多就是這個意思
下面來看代碼。
首先,我們先完成div的模擬代碼
<template><div class="selectWrap"> <div class="select-wrapper"> <div class="select" @click = "triggerOption"> <div class="select-content">{{selectContent.text}}</div> <div class="triangle-wrapper"> <div id="triangle-down"></div> </div> </div> <div class="option-wrapper" style="display: none;"> <div class="option-item" v-for = "(item,index) in subject" :key="index" @mouseout="out($event)" @mouseover="move($event)" @click = "choose(item)">{{item.text}}</div> </div> </div></div></template><script> export default{ data(){ return{ selectContent:{value:0,text:"小張"}, //模擬select默認選中的值 subject:[{value:0,text:"小張"},{value:1,text:"小李"}, //模擬option中的文本和value值 {value:2,text:"小王"},{value:4,text:"小明"}], } }, computed:{ optionWrapper(){ return document.querySelector(".option-wrapper"); }, selectCon(){ return document.querySelector(".select-content"); }, subjectList(){ return document.getElementsByClassName("option-item"); }, }, methods:{ move(event){ //模擬hover效果 for(var item of this.subjectList){ item.classList.remove("hover"); } event.currentTarget.classList.add("hover"); }, out(event){ event.currentTarget.classList.remove("hover"); }, triggerOption(){ //控制option的展示,以及選中后的高亮效果 if (this.optionWrapper.style.display == "none") { this.optionWrapper.style.display = "block"; }else{ this.optionWrapper.style.display = "none"; } for(var item of this.subjectList){ if (item.innerHTML == this.selectContent.text) { item.classList.add("hover"); }else{ item.classList.remove("hover"); } } }, choose(item){ //選中“option” this.selectContent.text = item.text; this.optionWrapper.style.display = "none"; } }, }</script><style> .selectWrap{ /*select的寬度*/ width: 100px; } .select{ position: relative; overflow: hidden; padding-right: 10px; min-width: 80px; width: 100%; height: 20px; line-height: 20px; border: 1px solid #000; cursor: default; font-size: 13px; } .select-content{ text-align: left; } .triangle-wrapper{ position: absolute; right: 0; top: 50%; transform: translateY(-50%); width: 18px; height: 20px; background-color: #fff; cursor: default; } #triangle-down{ position: absolute; right: 5px; top: 50%; transform: translateY(-50%); width: 0; height: 0; border-left: 3px solid transparent; border-right: 3px solid transparent; border-top: 6px solid #000; } .option-wrapper{ position: relative; overflow: hidden; min-width: 80px; width: 100%; border-right: 1px solid #000; border-bottom: 1px solid #000; border-left: 1px solid #000; } .option-item{ min-width: 80px; height: 20px; line-height: 20px; padding-right: 10px; text-align: left; cursor: default; } .hover{ background-color: rgb(30,144,255); color:#fff !important; }</style>
新聞熱點
疑難解答
圖片精選