您好,登錄后才能下訂單哦!
小編給大家分享一下Vue.js中如何制作自定義選擇組件,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
定制 select 標(biāo)簽的設(shè)計(jì)非常困難。有時(shí)候,如果不使用樣式化的 div 和自定義 JavaScript 的結(jié)合來(lái)構(gòu)建自己的腳本,那是不可能的。在本文中,你將學(xué)習(xí)如何構(gòu)建使用完全自定義 CSS 設(shè)置樣式的 Vue.js 組件。
Demo: https://codesandbox.io/s/custom-vuejs-select-component-8nqgd
HTML
<template> <div class="custom-select" :tabindex="tabindex" @blur="open = false" > <div class="selected" :class="{open: open}" @click="open = !open" > {{ selected }} </div> <div class="items" :class="{selectHide: !open}" > <div class="item" v-for="(option, i) of options" :key="i" @click="selected=option; open=false; $emit('input', option)" > {{ option }} </div> </div> </div> </template>
需要注意以下幾點(diǎn):
tabindex 屬性使我們的組件能夠得到焦點(diǎn),從而使它變得模糊。當(dāng)用戶在組件外部單擊時(shí), blur 事件將關(guān)閉我們的組件。
input 參數(shù)發(fā)出選定的選項(xiàng),父組件可以輕松地對(duì)更改做出反應(yīng)。
JavaScript
<script> export default { props:{ options:{ type: Array, required: true }, tabindex:{ type: Number, required: false, default: 0 } }, data() { return { selected: this.options.length > 0 ? this.options[0] : null, open: false }; }, mounted(){ this.$emit('input', this.selected); } }; </script>
另外,要注意的重要事項(xiàng):
我們還會(huì)在 mount 上發(fā)出選定的值,以便父級(jí)不需要顯式設(shè)置默認(rèn)值。如果我們的 select 組件是較大表單的一部分,那么我們希望能夠設(shè)置正確的 tabindex 。
CSS
<style scoped> .custom-select { position: relative; width: 100%; text-align: left; outline: none; height: 47px; line-height: 47px; } .selected { background-color: #080D0E; border-radius: 6px; border: 1px solid #858586; color: #ffffff; padding-left: 8px; cursor: pointer; user-select: none; } .selected.open{ border: 1px solid #CE9B2C; border-radius: 6px 6px 0px 0px; } .selected:after { position: absolute; content: ""; top: 22px; right: 10px; width: 0; height: 0; border: 4px solid transparent; border-color: #fff transparent transparent transparent; } .items { color: #ffffff; border-radius: 0px 0px 6px 6px; overflow: hidden; border-right: 1px solid #CE9B2C; border-left: 1px solid #CE9B2C; border-bottom: 1px solid #CE9B2C; position: absolute; background-color: #080D0E; left: 0; right: 0; } .item{ color: #ffffff; padding-left: 8px; cursor: pointer; user-select: none; } .item:hover{ background-color: #B68A28; } .selectHide { display: none; } </style>
該 CSS只是一個(gè)示例,你可以按照你的需求隨意修改樣式。
以上是“Vue.js中如何制作自定義選擇組件”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。