Vue.js 中制作自定义选择组件的代码附演示demo

Vue.js 中制作自定义选择组件的代码附演示demo

 

定制 select 标签的设计非常困难。有时候,如果不使用样式化的 div 和自定义 JavaScript 的结合来构建自己的脚本,那是不可能的。在本文中,你将学习如何构建使用完全自定义 CSS 设置样式的 Vue.js 组件。

Vue.js 中制作自定义选择组件的代码附演示demo

 

Demo: https://codesandbox.io/s/custom-vuejs-select-component-8nqgd

HTML

<template> <div :tabindex="tabindex" @blur="open = false" > <div :class="{open: open}" @click="open = !open" > {{ selected }} </div> <div :class="{selectHide: !open}" > <div v-for="(option, i) of options" :key="i" @click="selected=option; open=false; $emit('input', option)" > {{ option }} </div> </div> </div> </template>

需要注意以下几点:

tabindex 属性使我们的组件能够得到焦点,从而使它变得模糊。当用户在组件外部单击时, blur 事件将关闭我们的组件。

input 参数发出选定的选项,父组件可以轻松地对更改做出反应。

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>

另外,要注意的重要事项:

我们还会在 mount 上发出选定的值,以便父级不需要显式设置默认值。如果我们的 select 组件是较大表单的一部分,那么我们希望能够设置正确的 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只是一个示例,你可以按照你的需求随意修改样式。

我希望这可以帮助你创建自己的自定义选择组件,以下是完整组件要点的链接:

最后,在线演示的示例:https://codesandbox.io/s/custom-vuejs-select-component-8nqgd

总结

到此这篇关于Vue.js 中制作自定义选择组件的代码附演示demo的文章就介绍到这了,更多相关vuejs自定义选择组件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/7ebb023275fe65f3a8e193940d8273b0.html