This commit is contained in:
maplemei 2019-09-27 19:10:51 +08:00
parent cdce32f11f
commit 6feee42b47
21 changed files with 871 additions and 251 deletions

View File

@ -1,5 +1,22 @@
## 更新日志
### 1.0.4
*2019-09-27*
#### 新增
- 新增多选上限设置, 可以设置多选选中上限
- 新增工具条, 可以全选, 清空, 自定义
- 新增name设置, 可以表单提交, 隐藏input实现, 值为value逗号分隔
- 新增getValue参数, 可以获取不同类型的值
#### Bug fixes
- 修复搜索模式下输入中文不显示的问题
- 修改render不能及时渲染, 需要二次渲染的问题
- 修改IE下输入循环触发input事件的问题, IE 慎入
### 1.0.3
@ -41,4 +58,4 @@
#### Bug fixes
- 调整布局为flex布局
- 展开下拉选时, 自动聚焦搜索框
- 展开下拉选时, 自动聚焦搜索框

2
dist/static/2.js vendored

File diff suppressed because one or more lines are too long

2
dist/static/3.js vendored

File diff suppressed because one or more lines are too long

8
dist/static/docs.js vendored

File diff suppressed because one or more lines are too long

2
dist/xm-select.js vendored

File diff suppressed because one or more lines are too long

70
docs/mds/XM18.md Normal file
View File

@ -0,0 +1,70 @@
## 多选上限
### 最多选择2个
:::demo
```html
<div id="demo1" class="xm-select-demo"></div>
<script>
var demo1 = xmSelect.render({
el: '#demo1',
max: 2,
data: [
{name: '张三', value: 1, selected: true},
{name: '李四', value: 2, selected: true},
{name: '王五', value: 3},
]
})
</script>
```
:::
### 自定义选超的提示
:::demo
```html
<div id="demo2" class="xm-select-demo"></div>
<script>
var demo2 = xmSelect.render({
el: '#demo2',
max: 2,
maxMethod(seles, item){
alert(`${item.name}不能选了, 已经超了`)
},
data: [
{name: '张三', value: 1, selected: true},
{name: '李四', value: 2, selected: true},
{name: '王五', value: 3},
]
})
</script>
```
:::
### 自定义选超的闪烁颜色
:::demo
```html
<div id="demo3" class="xm-select-demo"></div>
<script>
var demo3 = xmSelect.render({
el: '#demo3',
max: 2,
theme: {
maxColor: 'orange',
},
data: [
{name: '张三', value: 1, selected: true},
{name: '李四', value: 2, selected: true},
{name: '王五', value: 3},
]
})
</script>
```
:::

111
docs/mds/XM19.md Normal file
View File

@ -0,0 +1,111 @@
## 工具条
### 默认工具条
:::demo
```html
<div id="demo1" class="xm-select-demo"></div>
<script>
var demo1 = xmSelect.render({
el: '#demo1',
toolbar: {
show: true,
},
filterable: true,
paging: true,
pageSize: 3,
data: [
{name: '张三', value: 1, selected: true},
{name: '李四', value: 2, selected: true},
{name: '王五', value: 3},
{name: '赵六', value: 4},
{name: '苹果', value: 5},
{name: '香蕉', value: 6},
{name: '凤梨', value: 7},
{name: '葡萄', value: 8},
{name: '樱桃', value: 9},
{name: '车厘子', value: 10},
{name: '火龙果', value: 11},
]
})
</script>
```
:::
### 隐藏图标
:::demo
```html
<div id="demo2" class="xm-select-demo"></div>
<script>
var demo2 = xmSelect.render({
el: '#demo2',
toolbar: {
show: true,
showIcon: false,
},
filterable: true,
paging: true,
pageSize: 3,
data: [
{name: '张三', value: 1, selected: true},
{name: '李四', value: 2, selected: true},
{name: '王五', value: 3},
{name: '赵六', value: 4},
{name: '苹果', value: 5},
{name: '香蕉', value: 6},
{name: '凤梨', value: 7},
{name: '葡萄', value: 8},
{name: '樱桃', value: 9},
{name: '车厘子', value: 10},
{name: '火龙果', value: 11},
]
})
</script>
```
:::
### 自定义工具条
:::demo
```html
<div id="demo3" class="xm-select-demo"></div>
<script>
var demo3 = xmSelect.render({
el: '#demo3',
toolbar: {
show: true,
list: ['ALL', {
name: '自定义',
icon: 'el-icon-star-off',
method(data){
alert('我是自定义的');
}
}]
},
filterable: true,
paging: true,
pageSize: 3,
data: [
{name: '张三', value: 1, selected: true},
{name: '李四', value: 2, selected: true},
{name: '王五', value: 3},
{name: '赵六', value: 4},
{name: '苹果', value: 5},
{name: '香蕉', value: 6},
{name: '凤梨', value: 7},
{name: '葡萄', value: 8},
{name: '樱桃', value: 9},
{name: '车厘子', value: 10},
{name: '火龙果', value: 11},
]
})
</script>
```
:::

99
docs/mds/ZM01.md Normal file
View File

@ -0,0 +1,99 @@
## 赋值与取值
### 给多选赋值
函数`setValue(array)`, 动态赋值多选选中的数据, array可以是value数组, 也可以是完整的object数组
:::demo
```html
<div id="demo1" class="xm-select-demo"></div>
<button class="btn" id="demo1-test1">赋值张三</button>
<button class="btn" id="demo1-test2">赋值张三(value方式)</button>
<button class="btn" id="demo1-test3">清空</button>
<pre id="demo1-result"></pre>
<script>
var demo1 = xmSelect.render({
el: '#demo1',
data: [
{name: '张三', value: 1},
{name: '李四', value: 2},
{name: '王五', value: 3},
]
})
document.getElementById('demo1-test1').onclick = function(){
demo1.setValue([
{name: '张三', value: 1},
])
};
document.getElementById('demo1-test2').onclick = function(){
demo1.setValue([ 1 ])
};
document.getElementById('demo1-test3').onclick = function(){
demo1.setValue([ ])
};
</script>
```
:::
### 取值
函数`getValue(type)`, type类型 name, nameStr, value, valueStr
:::demo
```html
<div id="demo2" class="xm-select-demo"></div>
<button class="btn" id="demo2-getValue">获取选中值</button>
<br/><br/>
<button class="btn" id="name">获取name数组</button>
<button class="btn" id="nameStr">获取name字符串</button>
<button class="btn" id="value">获取value数组</button>
<button class="btn" id="valueStr">获取value字符串</button>
<pre id="demo2-value"></pre>
<script>
var demo2 = xmSelect.render({
el: '#demo2',
data: [
{name: '张三', value: 1},
{name: '李四', value: 2},
{name: '王五', value: 3},
]
})
document.getElementById('demo2-getValue').onclick = function(){
//获取当前多选选中的值
var selectArr = demo2.getValue();
document.getElementById('demo2-value').innerHTML = JSON.stringify(selectArr, null, 2);
}
document.getElementById('name').onclick = function(){
//获取当前多选选中的值
var selectArr = demo2.getValue('name');
document.getElementById('demo2-value').innerHTML = JSON.stringify(selectArr, null, 2);
}
var types = ['name', 'nameStr', 'value', 'valueStr'];
types.forEach(function(type){
document.getElementById(type).onclick = function(){
//获取当前多选选中的值
var selectArr = demo2.getValue(type);
document.getElementById('demo2-value').innerHTML = JSON.stringify(selectArr, null, 2);
}
});
</script>
```
:::

50
docs/mds/ZM02.md Normal file
View File

@ -0,0 +1,50 @@
## 表单提交
### 默认表单提交
:::demo
```html
<form>
<div id="demo1" class="xm-select-demo"></div>
<button class="btn" type="submit">提交</button>
</form>
<script>
var demo1 = xmSelect.render({
el: '#demo1',
data: [
{name: '张三', value: 1},
{name: '李四', value: 2},
{name: '王五', value: 3},
]
})
</script>
```
:::
### 修改name
:::demo
```html
<form>
<div id="demo2" class="xm-select-demo"></div>
<button class="btn" type="submit">提交</button>
</form>
<script>
var demo2 = xmSelect.render({
el: '#demo2',
name: 'lalalalalala',
data: [
{name: '张三', value: 1},
{name: '李四', value: 2},
{name: '王五', value: 3},
]
})
</script>
```
:::

View File

@ -28,7 +28,7 @@
[![star](https://gitee.com/maplemei/xm-select/badge/star.svg?theme=dark)](https://gitee.com/maplemei/xm-select/stargazers)
[![fork](https://gitee.com/maplemei/xm-select/badge/fork.svg?theme=dark)](https://gitee.com/maplemei/xm-select/members)
[https://gitee.com/maplemei/xm-select](https://gitee.com/maplemei/xm-select)
[码云下载](https://gitee.com/maplemei/xm-select/releases)

View File

@ -32,6 +32,10 @@
| hide | 隐藏下拉的回调 | function | - | - |
| template | 自定义渲染选项 | function({ item, sels, name, value }) | - | - |
| on | 监听选中变化 | function({ arr, item, selected }) | - | - |
| max | 设置多选选中上限 | int | - | 0 |
| maxMethod | 达到选中上限的回到 | function(sels, item), sels: 已选中数据, item: 当前选中的值 | - | - |
| name | 表单提交时的name | string | - | select |
| toolbar | 工具条, 具体看下表 | object | - | - |
### prop
@ -46,9 +50,10 @@
### theme
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
| ----------------- | ------------------------------ | --------------- | ------ | ------ |
| color | 颜色 | string | - | #009688 |
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
| ------------ | --------- | --------------- | ------ | ------ |
| color | 主题颜色 | string | - | #009688 |
| maxColor | 选中上限闪烁边框颜色 | string | - | #e54d42 |
### model
@ -90,6 +95,37 @@ model: {
```
### toolbar
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
| ------------ | --------- | --------------- | ------ | ------ |
| show | 是否展示工具条 | boolean | true / false | false |
| showIcon | 是否显示工具图标 | boolean | true / false | true |
| list | 工具条数组 (默认有 全选/清空, 可以自定义) | array | - | [ "ALL", "CLEAR" ] |
- 自定义方式
```
list: [ "ALL", "CLEAR",
{
//显示图标, 可以是layui内置的图标, 也可以是自己引入的图标
//传入的icon会转化为 <i class="layui-icon layui-icon-face-smile"></i>
icon: 'layui-icon layui-icon-face-smile',
//显示名称
name: 'xxx',
//点击时触发的回调
method: function(data){
//data 当前页面的数据
}
}
]
```
### 方法
:::warning
@ -98,10 +134,10 @@ xmSelect.render()后会返回一个xmSelect对象, 可以进行方法调用
| 事件名 | 说明 | 参数 |
| ------ | ------------------ | -------- |
| getValue | 获取当前选中的数据 | - |
| setValue | 动态设置数据 | array: 选中的数据, show: 是否展开下拉 |
| getValue | 获取当前选中的数据 | (type: 类型), 可选值: name, nameStr, value, valueStr |
| setValue | 动态设置数据 | (array: 选中的数据, show: 是否展开下拉) |
| opened | 主动展开下拉 | - |
| closed | 主动关闭下拉 | - |
| render | 重新渲染多选 | (options):见配置项 |
| render | 重新渲染多选 | (options: 见配置项) |
| reset | 重置为上一次的render状态 | - |
| update | 更新多选选中, reset不保留 | - |

View File

@ -1,10 +1,16 @@
## 常见问题
### formSelects 与 xm-select
[formSelects](https://github.com/hnzzmsf/layui-formSelects/)是作者很久以前开发的一款多选插件, 在jQuery时代还是相对比较稳定, 不过性能上有很大的问题。痛并思痛后,开始学习其他开源组件的编写方案,最后决定重新开发。
[xm-select](https://gitee.com/maplemei/xm-select)作者精心二次开发的组件, 在formSelects的样式基础上进行了性能优化。目前看来还是比较稳定的 ^_^
### 1.在哪里下载
[Gitee码云下载](https://gitee.com/maplemei/xm-select), 使用时引入`xm-select.js`即可, 具体请看[入门指南](/#/component/install)
[Gitee码云下载](https://gitee.com/maplemei/xm-select/releases), 使用时引入`xm-select.js`即可, 已经内置了css, 具体请看[入门指南](/#/component/install)
### 2.为什么多选不显示
@ -14,4 +20,5 @@
### 3.渲染后还是不显示
打开控制台查看是否报错, 加群: 660408068, 询问
- 打开控制台查看是否报错
- 加群: 660408068, 询问

View File

@ -63,6 +63,17 @@ export default [{
{ path: '/example/XM15', name: '构建选项', component: importMd('/XM15') },
{ path: '/example/XM16', name: '监听选择', component: importMd('/XM16') },
{ path: '/example/XM17', name: '性能测试', component: importMd('/XM17') },
{ path: '/example/XM18', name: '多选上限', component: importMd('/XM18') },
{ path: '/example/XM19', name: '工具条', component: importMd('/XM19') },
]
}, {
path: '/example-custom',
name: '进阶示例',
redirect: '/example-custom/ZM01',
component: Component,
children: [
{ path: '/example-custom/ZM01', name: '赋值与取值', component: importMd('/ZM01') },
{ path: '/example-custom/ZM02', name: '表单提交', component: importMd('/ZM02') },
]
}, {
path: '/question',

View File

@ -1,7 +1,7 @@
{
"name": "xm-select",
"version": "1.0.0",
"description": "",
"version": "1.0.4",
"description": "始于Layui的select多选解决方案",
"main": "index.js",
"scripts": {
"dev": "cross-env NODE_ENV=dev node_modules/.bin/webpack-dev-server --config build/webpack.config.js",

View File

@ -1,67 +1,147 @@
/**
* 选中dom元素
*/
/**
* 选中dom元素
*/
export function selector(el) {
return document.querySelector(el);
}
/**
* 警告提示
*/
export function warn() {
let arr = [];
for (var i = 0; i < arguments.length; i++) {
arr.push(`${i + 1}. ${arguments[i]}`);
}
console.warn(arr.join('\n'));
}
/**
* 全局监听点击事件
*/
export function listenerClose(data, handler){
window.addEventListener('click', (e) => handler(e));
}
/**
* 安全拷贝数据
*/
export function safety(data){
return JSON.parse(JSON.stringify(data));
}
/**
* 检测对象是否为数组
*/
export function isArray(obj){
return Object.prototype.toString.call(obj) == "[object Array]";
return document.querySelector(el);
}
/**
* 警告提示
*/
export function warn() {
let arr = [];
for (var i = 0; i < arguments.length; i++) {
arr.push(`${i + 1}. ${arguments[i]}`);
}
console.warn(arr.join('\n'));
}
/**
* 全局监听点击事件
*/
export function listenerClose(data, handler) {
window.addEventListener('click', (e) => handler(e));
}
/**
* 安全拷贝数据
*/
export function safety(data) {
return JSON.parse(JSON.stringify(data));
}
/**
* 检测对象是否为数组
*/
export function isArray(obj) {
return Object.prototype.toString.call(obj) == "[object Array]";
}
/**
* 检测对象是否为函数
*/
export function isFunction(obj) {
return Object.prototype.toString.call(obj) == "[object Function]";
}
/**
* 转化为数字
*/
export function toNum(obj) {
obj -= 0;
isNaN(obj) && (obj = 0);
return obj;
}
/**
* 简单的深度合并
*/
export function deepMerge(obj1, obj2) {
let key;
for (key in obj2) {
// 如果target(也就是obj1[key])存在且是对象的话再去调用deepMerge否则就是obj1[key]里面没这个对象需要与obj2[key]合并
// 如果obj2[key]没有值或者值不是对象此时直接替换obj1[key]
obj1[key] =
obj1[key] &&
obj1[key].toString() === "[object Object]" &&
(obj2[key] && obj2[key].toString() === "[object Object]") ?
deepMerge(obj1[key], obj2[key]) :
(obj1[key] = obj2[key]);
}
return obj1;
}
/**
* 数组合并
*/
export function mergeArr(arr1, arr2, prop) {
let value = prop.value;
let result = [...arr2];
for (let i in arr1) {
let item = arr1[i];
if (!arr2.find(a => a[value] == item[value])) {
result.push(item);
}
}
return result;
}
export function watch(data) {
return new Promise((resolve, reject) => {
for (let key in data) {
let value = data[key];
Object.defineProperty(data, key, {
configurable: false, // 该状态下的属性描述符不能被修改和删除
enumerable: false, // 该状态下的属性描述符中的属性不可被枚举
get() {
return value;
},
set(newVal) {
if (newVal !== value) {
resolve(key, newVal, value);
value = newVal;
}
}
});
}
});
return new Promise((resolve, reject) => {
for (let key in data) {
let value = data[key];
Object.defineProperty(data, key, {
configurable: false, // 该状态下的属性描述符不能被修改和删除
enumerable: false, // 该状态下的属性描述符中的属性不可被枚举
get() {
return value;
},
set(newVal) {
if (newVal !== value) {
resolve(key, newVal, value);
value = newVal;
}
}
});
}
});
}
export function checkUserAgent() {
const ua = navigator.userAgent;
if (ua.indexOf('Mac OS') != -1) {
return 'mac';
}
return 'win';
}
export function IEVersion() {
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
if (isIE) {
var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
reIE.test(userAgent);
var fIEVersion = parseFloat(RegExp["$1"]);
if (fIEVersion == 7) {
return 7;
} else if (fIEVersion == 8) {
return 8;
} else if (fIEVersion == 9) {
return 9;
} else if (fIEVersion == 10) {
return 10;
} else {
return 6; //IE版本<=7
}
} else if (isEdge) {
return 'edge'; //edge
} else if (isIE11) {
return 11; //IE11
} else {
return -1; //不是ie浏览器
}
}
export function checkUserAgent(){
const ua = navigator.userAgent;
if(ua.indexOf('Mac OS') != -1){
return 'mac';
}
return 'win';
}

View File

@ -5,10 +5,12 @@ const lanSetting = { zn, en }
export default function (lan = 'zn') {
let setting = lanSetting[lan] || zn;
return {
//多选数据
data: [],
//表单提交的name
name: 'select',
//默认选中数据, 优先级大于selected
initValue: null,
//默认提示
@ -48,6 +50,15 @@ export default function (lan = 'zn') {
repeat: false,
//是否点击选项后自动关闭下拉框
clickClose: false,
//多选上限
max: 0,
maxMethod: function(sels, item){},
//工具条
toolbar: {
show: false,
showIcon: true,
list: [ 'ALL', 'CLEAR' ],
},
//自定义属性名称
prop: {
name: 'name',
@ -57,7 +68,8 @@ export default function (lan = 'zn') {
},
//主题配置
theme: {
color: '#009688',
color: '#009688', //默认主题颜色
maxColor: '#e54d42', //多选上限边框闪烁颜色
},
//模型
model: {
@ -79,22 +91,22 @@ export default function (lan = 'zn') {
},
},
},
// 展开下拉框
show(){
},
// 隐藏下拉框
hide(){
},
// 模板组成, 当前option数据, 已经选中的数据, name, value
// 模板组成, 当前option数据, 已经选中的数据, name, value
template({ item, sels, name, value }){
return name;
},
//监听选中事件
on({ arr, item, selected }){
}
}
}
}

View File

@ -1,6 +1,6 @@
import { h, Component, render } from '@/components/preact'
import Framework from '@/components/element/framework'
import { selector, warn, listenerClose, watch, safety, isArray } from '@/components/common/util'
import { selector, warn, listenerClose, watch, safety, isArray, deepMerge } from '@/components/common/util'
import defaultOptions from '@/components/config/options'
@ -30,15 +30,15 @@ class xmOptions {
//定义默认值
this.options = defaultOptions(options.language);
//开始渲染数据
this.update(options, true);
this.update(options);
}
/**
* 更新数据 + 重新渲染
*/
update(options = {}, isNew){
update(options = {}){
//记录最新的配置项
this.options = {...this.options, ...options};
this.options = deepMerge(this.options, options);
//如果dom不存在, 则不进行渲染事项
let dom = selector(this.options.el);
@ -46,16 +46,10 @@ class xmOptions {
warn(`没有找到渲染对象: ${options.el}, 请检查`)
return ;
}
//如果是历史渲染过的数据, 重置一下数据
isNew && childs[this.options.el] && childs[this.options.el].reset();
let isRender = false;
const onRef = (ref) => childs[this.options.el] = ref;
const onReset = result => {
this.options.data = result;
}
render(<Framework { ...this.options } onReset={ onReset } onClose={ onClose } onRef={ onRef } />, dom);
render(<Framework { ...this.options } onClose={ onClose } onRef={ onRef } />, dom);
//记录数据
data[this.options.el] = this;
@ -98,8 +92,23 @@ class xmOptions {
/**
* 获取多选选中的数据
*/
getValue(){
return safety(childs[this.options.el].state.sels);
getValue(type){
let arr = safety(childs[this.options.el].state.sels);
if(type === 'name'){
return arr.map(item => item[this.options.prop.name]);
}else
if(type === 'nameStr'){
return arr.map(item => item[this.options.prop.name]).join(',');
}else
if(type === 'value'){
return arr.map(item => item[this.options.prop.value]);
}else
if(type === 'valueStr'){
return arr.map(item => item[this.options.prop.value]).join(',');
}
return arr;
}
/**

View File

@ -1,5 +1,5 @@
import { h, Component, render } from '@/components/preact'
import { checkUserAgent } from '@/components/common/util'
import { checkUserAgent, isFunction, toNum } from '@/components/common/util'
//渲染类
import Tips from './tips';
@ -10,31 +10,33 @@ import General from './model/general';
* 框架渲染类, 渲染基础的外边框 + 属性变化监听
*/
class Framework extends Component{
constructor(options){
super(options);
//初始化多选数据
this.reset();
this.reset(this.props);
//回传子组件
this.props.onRef(this);
this.bodyView = null;
}
reset(){
let selected = this.props.prop.selected;
this.value(this.props.initValue ? this.props.initValue : this.props.data.filter(item => item[selected]), false);
this.resetDate(this.props.data);
reset(props){
//用于多选上限的边框颜色变化
this.updateBorderColor('');
this.resetDate(props.data);
let selected = props.prop.selected;
this.value(props.initValue ? props.initValue : this.state.data.filter(item => item[selected]), false);
}
resetDate(data = []){
this.setState({ data });
}
value(sels, show){
let data = this.props.data;
let data = this.state.data;
let value = this.props.prop.value;
let direction = this.props.direction;
this.setState({
this.setState({
sels: sels.map(sel => typeof sel === 'object' ? sel[value] : sel).map(val => data.find(item => item[value] == val)).filter(a => a),
//下拉框是否展开
show,
@ -43,36 +45,47 @@ class Framework extends Component{
directionVal: '',
})
}
onReset(data){
this.resetDate(data);
updateBorderColor(tmpColor){
this.setState({ tmpColor });
}
onReset(data, type){
//重置数据
if(type === 'data'){
this.resetDate(data);
}else
//重置选中数据
if(type === 'sels'){
this.setState({ sels: data });
}
}
onClick(e){
let show = !this.state.show;
if(show){
if(this.props.show && this.props.show() == false){
return;
}
//事件互斥原则, 打开一个多选, 关闭其他所有多选
this.props.onClose(this.props.el);
let direction = this.state.direction;
if(direction === 'auto'){
//用于控制js获取下拉框的高度
this.bodyView.style.display = 'block';
this.bodyView.style.visibility = 'hidden';
//获取下拉元素的高度
let bodyViewRect = this.bodyView.getBoundingClientRect();
let bodyViewHeight = bodyViewRect.height;
//还原控制效果
this.bodyView.style.display = '';
this.bodyView.style.visibility = '';
//确定下拉框是朝上还是朝下
let clientHeight = document.documentElement.clientHeight;
let rect = this.base.getBoundingClientRect();
@ -87,20 +100,20 @@ class Framework extends Component{
//如果产生滚动条, 关闭下拉后回到顶部
this.bodyView.scroll && this.bodyView.scroll(0, 0);
}
this.setState({ show });
//阻止其他绑定事件的冒泡
e && e.stopPropagation();
}
componentWillReceiveProps(props){
this.resetDate(props.data);
this.reset(props)
}
render(config, { sels, show }) {
const { tips, theme, prop, style, radio, repeat, clickClose, on } = config;
const borderStyle = { borderColor: theme.color };
const { tips, theme, prop, style, radio, repeat, clickClose, on, max, maxMethod } = config;
const borderStyle = { borderColor: this.state.tmpColor || theme.color };
//最外层边框的属性
const xmSelectProps = {
style: {
@ -120,18 +133,29 @@ class Framework extends Component{
}
//普通多选数据
const valueProp = prop.value;
//选项, 选中状态, 禁用状态, 是否强制删除:在label上点击删除
const ck = (item, selected, disabled, mandatoryDelete) => {
//如果是禁用状态, 不能进行操作
if(disabled) return;
//查看是否设置了多选上限
let maxCount = toNum(max);
if(maxCount > 0 && sels.length >= maxCount){
this.updateBorderColor(theme.maxColor);
//恢复正常
setTimeout(() => this.updateBorderColor(''), 300);
//查看是否需要回调
maxMethod && isFunction(maxMethod) && maxMethod(sels, item);
return ;
}
//如果现在是选中状态
if(selected && (!repeat || mandatoryDelete)){
let index = sels.findIndex(sel => sel[valueProp] == item[valueProp])
if(index != -1){
sels.splice(index, 1);
this.setState(sels);
this.setState({ sels });
}
}else{
//如果是单选模式
@ -141,20 +165,25 @@ class Framework extends Component{
this.setState({ sels: [...sels, item] });
}
}
on && on({ arr: this.state.sels, item, selected: !selected });
//检查是否为选择即关闭状态, 强制删除情况下不做处理
clickClose && !mandatoryDelete && this.onClick();
};
const select = (
<input class="xm-select-default" name={ config.name } value={ sels.map(item => item[prop.value]).join(',') }></input>
)
const labelProps = { ...config, data: this.state.data, sels, ck, title: sels.map(sel => sel[prop.name]).join(',') }
const bodyProps = { ...config, data: this.state.data, sels, ck, show, onReset: this.onReset.bind(this) }
//控制下拉框的显示于隐藏
const bodyClass = ['xm-body', this.state.directionVal, show ? '' : 'dis'].join(' ');
return (
<xm-select { ...xmSelectProps } >
{ select }
<i class={ iconClass } />
<Tips { ...tipsProps } />
<Label { ...labelProps } />
@ -166,4 +195,4 @@ class Framework extends Component{
}
}
export default Framework;
export default Framework;

View File

@ -1,36 +1,37 @@
import { h, Component, render } from '@/components/preact'
import { isFunction, safety, mergeArr, IEVersion } from '@/components/common/util'
/**
* 普通的多选渲染
*/
class General extends Component{
constructor(options){
super(options);
this.searchCid = 0;
this.setState({
this.setState({
searchValue: '',
filterValue: '',
remote: true,
loading: false,
pageIndex: 1,
pageSize: 10,
inputOver: true,
});
}
optionClick(item, selected, disabled, e){
this.props.ck(item, selected, disabled);
//阻止父组件上的事件冒泡
this.blockClick(e);
}
blockClick(e){
e.stopPropagation();
}
pagePrevClick(e){
let index = this.state.pageIndex;
if(index <= 1){
@ -45,51 +46,53 @@ class General extends Component{
}
this.changePageIndex(index + 1);
}
changePageIndex(index){
this.setState({
pageIndex: index
})
}
searchInput(e){
let v = e.target.value;
console.log(v, this.state.searchValue)
setTimeout(() => {
if(this.state.inputOver){
//保证输入框内的值是实时的
this.setState({ searchValue: v });
//让搜索变成异步的
clearTimeout(this.searchCid);
this.searchCid = setTimeout(() => this.setState({
filterValue: this.state.searchValue,
remote: true,
}), this.props.delay);
}
}, 0)
if(v === this.state.searchValue){
return ;
}
clearTimeout(this.searchCid);
if(this.state.inputOver){
//保证输入框内的值是实时的
this.setState({ searchValue: v });
//让搜索变成异步的
this.searchCid = setTimeout(() => this.setState({
filterValue: this.state.searchValue,
remote: true,
}), this.props.delay);
}
}
focus(){
this.searchInputRef && this.searchInputRef.focus();
}
blur(){
this.searchInputRef && this.searchInputRef.blur();
}
handleComposition(e){
let type = e.type;
if(type === 'compositionstart'){
this.setState({ inputOver: false })
clearTimeout(this.searchCid);
}else if(type === 'compositionend'){
this.setState({ inputOver: true })
this.searchInput(e);
}
}
componentWillReceiveProps(props){
if(this.props.show != props.show){
if(!props.show){
@ -101,13 +104,13 @@ class General extends Component{
}
}
}
render(config) {
let { data, prop, template, theme, radio, sels, empty, filterable, filterMethod, remoteSearch, remoteMethod, delay, searchTips } = config
const { name, value, disabled } = prop;
let arr = data;
//是否开启了搜索
if(filterable){
@ -119,89 +122,123 @@ class General extends Component{
remoteMethod(this.state.filterValue, result => {
//回调后可以重新聚焦
this.focus();
this.setState({ loading: false });
this.props.onReset(result);
this.props.onReset(result, 'data');
});
}
}else{
arr = data.filter((item, index) => filterMethod(this.state.filterValue, item, index, prop));
}
}
const searchClass = ['xm-search', filterable ? '':'dis'].join(' ');
const search = (
<div class={ searchClass }>
<div class='xm-search'>
<i class="xm-iconfont xm-icon-sousuo"></i>
<input type="text" class="xm-input xm-search-input" placeholder={ searchTips } value={ this.state.searchValue }
ref={ (input) => { this.searchInputRef = input; } }
onClick={ this.blockClick.bind(this) }
onInput={ this.searchInput.bind(this) }
<input type="text" class="xm-input xm-search-input" placeholder={ searchTips } value={ this.state.searchValue }
ref={ input => this.searchInputRef = input }
onClick={ this.blockClick.bind(this) }
onInput={ this.searchInput.bind(this) }
onCompositionStart={ this.handleComposition.bind(this) }
onCompositionUpdate={ this.handleComposition.bind(this) }
onCompositionEnd={ this.handleComposition.bind(this) }
/>
</div>
);
let paging = '';
if(config.paging){
//计算当前分页的总页码
const size = Math.floor((arr.length - 1) / config.pageSize) + 1;
//如果当前页码大于总页码, 重置一下
if(this.state.pageIndex > size){
this.changePageIndex(size);
}
//如有总页码>1, 但是因为搜索造成的页码=0的情况
if(size > 0 && this.state.pageIndex <= 0){
this.changePageIndex(1);
}
//实现简单的物理分页
let start = (this.state.pageIndex - 1) * config.pageSize;
let end = start + config.pageSize;
arr = arr.slice(start, end);
const disabledStyle = {cursor: 'no-drop', color: '#d2d2d2'};
let prevStyle = {}, nextStyle = {};
this.state.pageIndex <= 1 && (prevStyle = disabledStyle);
this.state.pageIndex == size && (nextStyle = disabledStyle);
const defaultCurrClass = {
position: 'relative',
borderRadius: '1px',
}
const pagingClass = 'xm-paging';
// {
// ''.padEnd(size, ' ').split('').map((s, i) => (
// <span style={
// this.state.pageIndex == i + 1 ? {
// ...defaultCurrClass,
// backgroundColor: theme.color,
// this.state.pageIndex == i + 1 ? {
// ...defaultCurrClass,
// backgroundColor: theme.color,
// borderColor: theme.color,
// color: '#FFF',
// } : defaultCurrClass
// } : defaultCurrClass
// }>{ i + 1 }</span>
// ))
// }
paging = (
<div class={ pagingClass }>
<div class='xm-paging'>
<span style={ prevStyle } onClick={ this.pagePrevClick.bind(this) }>上一页</span>
<span>{ this.state.pageIndex } / { size }</span>
<span style={ nextStyle } onClick={ e => this.pageNextClick.bind(this, e, size)() }>下一页</span>
</div>
)
}
let safetyArr = safety(arr);
//工具条操作
const toolbar = (
<div class='xm-toolbar'>
{ config.toolbar.list.map(tool => {
const toolClass = 'toolbar-tag';
let info;
if(tool === 'ALL'){
info = { icon: 'xm-iconfont xm-icon-quanxuan', name: '全选', method: (data) => {
this.props.onReset(mergeArr(data, sels, prop), 'sels');
} };
}else if(tool === 'CLEAR'){
info = { icon: 'xm-iconfont xm-icon-qingkong', name: '清空', method: (data) => {
this.props.onReset([], 'sels');
} };
}else {
info = tool
}
const hoverChange = e => {
if(e.type === 'mouseenter') e.target.style.color = theme.color;
if(e.type === 'mouseleave') e.target.style.color = '';
}
return (<div class={ toolClass } onClick={ () => {
isFunction(info.method) && info.method(safetyArr)
} } onMouseEnter={ hoverChange } onMouseLeave={ hoverChange }>
{ config.toolbar.showIcon && <i class={ info.icon }></i> }
<span>{ info.name }</span>
</div>)
}).filter(a => a) }
</div>
)
arr = arr.map(item => {
const selected = !!sels.find(sel => sel[value] == item[value])
const iconStyle = selected ? {
color: theme.color,
@ -212,26 +249,27 @@ class General extends Component{
};
const className = ['xm-option', (item[disabled] ? ' disabled' : ''), (selected ? ' selected' : '')].join(' ');
const iconClass = ['xm-option-icon xm-iconfont', radio ? 'xm-icon-danx' : 'xm-icon-duox'].join(' ');
return (
<div class={className} value={ item[value] } onClick={ this.optionClick.bind(this, item, selected, item[disabled]) }>
<i class={ iconClass } style={ iconStyle }></i>
<div class='xm-option-content' dangerouslySetInnerHTML={{ __html: template({ data, item, arr: sels, name: item[name], value: item[value] }) }}></div>
</div>
)
})
})
if(!arr.length){
arr.push(
<div class="xm-select-empty">{ empty }</div>
)
}
return (
<div onClick={ this.blockClick }>
<div onClick={ this.blockClick }>
<div>
{ search }
<div style={ {maxHeight: config.height, overflow: 'auto'} }>{ arr }</div>
{ config.toolbar.show && toolbar }
{ filterable && search }
<div class="scroll-body" style={ {maxHeight: config.height} }>{ arr }</div>
{ config.paging && paging }
</div>
{ this.state.loading && <div class="loading" >
@ -242,4 +280,4 @@ class General extends Component{
}
}
export default General;
export default General;

View File

@ -36,19 +36,19 @@
xm-select{
*{
margin: 0;
padding: 0;
box-sizing: border-box;
margin: 0;
padding: 0;
box-sizing: border-box;
font-size: 14px;
font-weight: 400;
color: @fontColor;
// color: @fontColor;
text-overflow: ellipsis;
user-select: none;
-ms-user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
}
background-color: #FFF;
position: relative;
border: @border;
@ -58,18 +58,18 @@ xm-select{
display: block;
width: 100%;
cursor: pointer;
&:hover{
border-color: #C0C4CC;
}
& > .xm-tips{
color: #999999;
padding: 0 10px;
height: 100%;
}
}
& > .xm-icon{
display: inline-block;
overflow: hidden;
@ -86,12 +86,12 @@ xm-select{
transition: all .3s;
-webkit-transition: all .3s
}
& > .xm-icon-expand{
margin-top: -9px;
transform: rotate(180deg);
}
& > .xm-label{
// padding: 0 30px 0 10px;
position: absolute;
@ -100,10 +100,10 @@ xm-select{
left: 10px;
right: 30px;
overflow: auto hidden;
.scroll{
overflow-y: hidden;
.label-content{
height: calc(100% - 20px);
display: flex;
@ -114,7 +114,7 @@ xm-select{
}
}
}
.xm-label-block{
display: flex;
position: relative;
@ -125,13 +125,13 @@ xm-select{
border-radius: 3px;
align-items: baseline;
color: #FFF;
& > span{
display: flex;
color: #FFF;
white-space: nowrap;
}
& > i{
color: #FFF;
margin-left: 8px;
@ -139,7 +139,7 @@ xm-select{
cursor: pointer;
display: flex;
}
&.disabled{
background-color: @disabledColor !important;
cursor: no-drop !important;
@ -149,7 +149,7 @@ xm-select{
}
}
}
& > .xm-body {
position: absolute;
left: 0;
@ -167,23 +167,38 @@ xm-select{
animation-name: xm-upbit;
animation-duration: .3s;
animation-fill-mode: both;
.scroll-body{
overflow: auto;
.scrollBorder() {
-webkit-border-radius: 2em;
-moz-border-radius: 2em;
-ms-border-radius: 2em;
border-radius:2em;
}
&::-webkit-scrollbar{ width: 8px; }
&::-webkit-scrollbar-track{ .scrollBorder(); background-color: #FFF; }
&::-webkit-scrollbar-thumb{ .scrollBorder(); background-color: #C2C2C2; }
}
&.up{
top: auto;
bottom: 42px;
}
.xm-option{
display: flex;
align-items: center;
position: relative;
padding: 0 10px;
cursor: pointer;
&:hover{
background-color: #f2f2f2;
}
&-icon{
color: transparent;
display: flex;
@ -197,7 +212,7 @@ xm-select{
&-icon.xm-icon-danx{
border-radius: 100%;
}
&-content{
display: flex;
position: relative;
@ -205,16 +220,16 @@ xm-select{
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
color: #666;
color: @fontColor;
width: calc(100% - 20px);
}
}
.xm-select-empty{
text-align: center;
color: #999;
}
.disabled{
cursor: no-drop;
&:hover{
@ -226,23 +241,24 @@ xm-select{
.xm-option-content{
color: @disabledColor !important;
}
&.selected>.xm-option-icon{
color: @disabledColor !important;
}
}
.xm-search{
background-color: #FFF !important;
position: relative;
padding: 0 10px;
margin-bottom: 5px;
cursor: pointer;
&>i{
position: absolute;
color: @fontColor;
}
&-input{
border: none;
border-bottom: 1px solid #E6E6E6;
@ -250,19 +266,19 @@ xm-select{
cursor: text;
}
}
.xm-paging{
padding: 0 10px;
display: flex;
margin-top: 5px;
&>span:first-child{
border-radius: 2px 0 0 2px;
}
&>span:last-child{
border-radius: 0 2px 2px 0
}
&>span{
display: flex;
flex: auto;
@ -278,8 +294,39 @@ xm-select{
border: 1px solid #e2e2e2;
}
}
.xm-toolbar{
padding: 0 10px;
display: flex;
margin: -3px 0;
cursor: default;
.toolbar-tag{
cursor: pointer;
display: flex;
margin-right: 20px;
color: @fontColor;
align-items: baseline;
&:hover{
opacity: .8;
}
&:active{
opacity: 1;
}
&>i{
margin-right: 2px;
font-size: 14px;
}
&:last-child{
margin-right: 0;
}
}
}
}
.xm-input{
cursor: pointer;
border-radius: 2px;
@ -295,11 +342,11 @@ xm-select{
padding-left: 10px;
outline: 0;
}
.dis{
display: none;
}
.loading{
position: absolute;
top: 0;
@ -310,15 +357,15 @@ xm-select{
display: flex;
align-items: center;
justify-content: center;
.loader{
border: .2em dotted currentcolor;
border-radius: 50%;
-webkit-animation: 1s loader linear infinite;
animation: 1s loader linear infinite;
display: inline-block;
width: 1em;
height: 1em;
@ -327,7 +374,11 @@ xm-select{
pointer-events: none;
}
}
.xm-select-default{
display: none !important;
}
}
// xm-select[ua='win']{
@ -335,4 +386,4 @@ xm-select{
// margin-top: 0px;
// margin-bottom: -2px;
// }
// }
// }