网络编程 
首页 > 网络编程 > 浏览文章

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

(编辑:jimmy 日期: 2024/5/8 浏览:3 次 )

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
 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>

需要注意以下几点:

  • 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 "htmlcode">
<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自定义组件的四种方式示例详解
下一篇:使用vue-cli3+typescript的项目模板创建工程的教程
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网