做者:Lane Wagner翻译:疯狂的技术宅javascript
原文:https://hackernoon.com/how-to...css
未经容许严禁转载html
定制 select 标签的设计很是困难。有时候,若是不使用样式化的 div 和自定义 JavaScript 的结合来构建本身的脚本,那是不可能的。在本文中,你将学习如何构建使用彻底自定义 CSS 设置样式的 Vue.js 组件。前端
Demo: https://codesandbox.io/s/cust...vue
<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>
须要注意如下几点:java
tabindex
属性使咱们的组件可以获得焦点,从而使它变得模糊。当用户在组件外部单击时,blur
事件将关闭咱们的组件。input
参数发出选定的选项,父组件能够轻松地对更改作出反应。<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>
另外,要注意的重要事项:程序员
咱们还会在 mount
上发出选定的值,以便父级不须要显式设置默认值。若是咱们的 select 组件是较大表单的一部分,那么咱们但愿可以设置正确的 tabindex 。面试
<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只是一个示例,你能够按照你的需求随意修改样式。segmentfault
我但愿这能够帮助你建立本身的自定义选择组件,如下是完整组件要点的连接:服务器
最后,在线演示的示例:https://codesandbox.io/s/cust...