前言
最近接了一个需求,基于 ElementUI的选择器,自定义符合需求的样式出来,笔者最终顺利完成了需求,其中踩了不少坑,写本分分享下
案例
首先展示下本demo的代码结构,以便后续观具体代码,心中数
本项目是基于 ElementUI 的 Starter,这个可以开箱即用,里边搭建好 Vue,ElementUI的架子,方便开发者进行后续的开发,不用浪费精力在配置上,具体地址如下:
https://github.com/ElementUI/element-starter
全部代码如下
<template> <div id="app"> <el-select v-model="value" multiple filterable remote reserve-keyword placeholder="请输入关键词" :remote-method="remoteMethod" :loading="loading"> <el-option v-for="item in options" :key="item.name" :label="item.name" :value="item.name" style="height:100%"> <div> <span class="test-name">{{ item.name }}</span> <div class="test-country">{{ item.country }}</div> </div> </el-option> </el-select> </div> </template> <script> export default { data() { return { options: [], value: [], list: [], loading: false, states: [ { name: "吕不韦", country: "战国时期-秦国-丞相" }, { name: "蒙恬", country: "战国时期-秦国-名将" }, { name: "毛遂", country: "战国时期-赵国-平原君门客" }, { name: "蒙骜", country: "战国时期-秦国-蒙恬的祖父" }, ] } }, mounted() { this.list = this.states.map(item => { return {name: `${item.name}`, country: `${item.country}`}; }); }, methods: { remoteMethod(query) { if (query !== '') { this.loading = true; setTimeout(() => { this.loading = false; this.options = this.list.filter(item => { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1; }); }, 200); } else { this.options = []; } } } } </script> <style scoped> /* 修改ElementUI框架的样式 */ .el-select-dropdown__item { font-size: 14px; padding: 0 20px; position: relative; white-space: nowrap; text-overflow: ellipsis; color: #606266; height: 34px; line-height: 34px; -webkit-box-sizing: border-box; box-sizing: border-box; cursor: pointer; } /* 人物 */ .test-name { color: #409eff; font-weight: 700; } /* 国家 */ .test-country { line-height: 1.5; color: #ccc; font-size: 12px; } </style>
后面具体分析
效果
先来看下效果,读代码时候,更加有侧重点:
本demo,在输入框中,输入“蒙”,下面的每个选项,内容不止一行,并且附带我们想要的样式,如颜色,字体大小等
代码要点
1.选择器选项全面显示
<el-option v-for="item in options" :key="item.name" :label="item.name" :value="item.name" style="height:100%"> <div>
这里 style="height:100%",可以全面显示每个选项的内容,不会只显示一行,遮挡住你想要展示 的内容,很重要!你可以因此丰富你的单选项内容。
2.选择器选项样式设置
这里选择覆盖 el-select-dropdown__item 的样式,从而起到修改选项样式(字体,颜色等)的作用!
/* 修改ElementUI框架的样式 */ .el-select-dropdown__item { font-size: 14px; padding: 0 20px; position: relative; white-space: nowrap; text-overflow: ellipsis; color: #606266; height: 34px; line-height: 34px; -webkit-box-sizing: border-box; box-sizing: border-box; cursor: pointer; }
其他
基于他人的框架如 ElementUI 进行开发,方便的使用功能、样式的同时,多了许多的束缚,我们不得不遵循他们的逻辑,才能往我们个性化的需求方向靠拢。