瘋狂的技術宅 前端先鋒 前端
翻譯:瘋狂的技術宅
做者:Lane Wagner
來源:hackernoon
正文共:2337 字
預計閱讀時間:7 分鐘vue
定製 select 標籤的設計很是困難。有時候,若是不使用樣式化的 div 和自定義 JavaScript 的結合來構建本身的腳本,那是不可能的。在本文中,你將學習如何構建使用徹底自定義 CSS 設置樣式的 Vue.js 組件。ide
Demo: https://codesandbox.io/s/custom-vuejs-select-component-8nqgd學習
1<template> 2 <div 3 class="custom-select" 4 :tabindex="tabindex" 5 @blur="open = false" 6 > 7 <div 8 class="selected" 9 :class="{open: open}" 10 @click="open = !open" 11 > 12 {{ selected }} 13 </div> 14 <div 15 class="items" 16 :class="{selectHide: !open}" 17 > 18 <div 19 class="item" 20 v-for="(option, i) of options" 21 :key="i" 22 @click="selected=option; open=false; $emit('input', option)" 23 > 24 {{ option }} 25 </div> 26 </div> 27 </div> 28</template>
須要注意如下幾點:ui
1<script> 2export default { 3 props:{ 4 options:{ 5 type: Array, 6 required: true 7 }, 8 tabindex:{ 9 type: Number, 10 required: false, 11 default: 0 12 } 13 }, 14 data() { 15 return { 16 selected: this.options.length > 0 ? this.options[0] : null, 17 open: false 18 }; 19 }, 20 mounted(){ 21 this.$emit('input', this.selected); 22 } 23}; 24</script>
另外,要注意的重要事項:this
咱們還會在 mount 上發出選定的值,以便父級不須要顯式設置默認值。若是咱們的 select 組件是較大表單的一部分,那麼咱們但願可以設置正確的 tabindex 。spa
1<style scoped> 2 3.custom-select { 4 position: relative; 5 width: 100%; 6 text-align: left; 7 outline: none; 8 height: 47px; 9 line-height: 47px; 10} 11 12.selected { 13 background-color: #080D0E; 14 border-radius: 6px; 15 border: 1px solid #858586; 16 color: #ffffff; 17 padding-left: 8px; 18 cursor: pointer; 19 user-select: none; 20} 21 22.selected.open{ 23 border: 1px solid #CE9B2C; 24 border-radius: 6px 6px 0px 0px; 25} 26 27.selected:after { 28 position: absolute; 29 content: ""; 30 top: 22px; 31 right: 10px; 32 width: 0; 33 height: 0; 34 border: 4px solid transparent; 35 border-color: #fff transparent transparent transparent; 36} 37 38.items { 39 color: #ffffff; 40 border-radius: 0px 0px 6px 6px; 41 overflow: hidden; 42 border-right: 1px solid #CE9B2C; 43 border-left: 1px solid #CE9B2C; 44 border-bottom: 1px solid #CE9B2C; 45 position: absolute; 46 background-color: #080D0E; 47 left: 0; 48 right: 0; 49} 50 51.item{ 52 color: #ffffff; 53 padding-left: 8px; 54 cursor: pointer; 55 user-select: none; 56} 57 58.item:hover{ 59 background-color: #B68A28; 60} 61 62.selectHide { 63 display: none; 64} 65</style>
該 CSS只是一個示例,你能夠按照你的需求隨意修改樣式。翻譯
我但願這能夠幫助你建立本身的自定義選擇組件,如下是完整組件要點的連接:設計
最後,在線演示的示例:https://codesandbox.io/s/custom-vuejs-select-component-8nqgdcode
原文連接
https://hackernoon.com/how-to-make-a-custom-select-component-in-vuejs-8kt32pj