u-picker.vue 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. <template>
  2. <u-popup :maskCloseAble="maskCloseAble" mode="bottom" :popup="false" v-model="value" length="auto" :safeAreaInsetBottom="safeAreaInsetBottom" @close="close" :z-index="uZIndex">
  3. <view class="u-datetime-picker">
  4. <view class="u-picker-header" @touchmove.stop.prevent="">
  5. <view class="u-btn-picker u-btn-picker--tips"
  6. :style="{ color: cancelColor }"
  7. hover-class="u-opacity"
  8. :hover-stay-time="150"
  9. @tap="getResult('cancel')"
  10. >{{cancelText}}</view>
  11. <view class="u-picker__title" v-if="range.length<5" >{{ title }}</view>
  12. <view class="u-picker__title" v-else >
  13. <u-input v-model="querykey" placeholder="输入内容查询" type="text" :border="true" />
  14. </view>
  15. <view
  16. class="u-btn-picker u-btn-picker--primary"
  17. :style="{ color: moving ? cancelColor : confirmColor }"
  18. hover-class="u-opacity"
  19. :hover-stay-time="150"
  20. @touchmove.stop=""
  21. @tap.stop="getResult('confirm')"
  22. >
  23. {{confirmText}}
  24. </view>
  25. </view>
  26. <view class="u-picker-body" v-if="range.length<5">
  27. <picker-view :value="valueArr" @change="change" class="u-picker-view" @pickstart="pickstart" @pickend="pickend">
  28. <picker-view-column v-if="!reset">
  29. <view class="u-column-item" v-for="(item, index) in range" :key="index">
  30. <view class="u-line-1">{{ getItemValue(item, 'selector') }}</view>
  31. </view>
  32. </picker-view-column>
  33. </picker-view>
  34. </view>
  35. <view v-else>
  36. <scroll-view scroll-y="true" class="scroll-Y" >
  37. <view class="u-list-body">
  38. <view class="u-list-item" v-for="(item, index) in queryrange"
  39. :class="{
  40. 'list-index':valueArr[0]==index
  41. }"
  42. @click="valueArr=[index],$forceUpdate()"
  43. :key="index">
  44. <view class="u-line-1">{{ getItemValue(item, 'selector') }}</view>
  45. </view>
  46. </view>
  47. <u-divider color="#B6BDC3" v-if="queryrange.length"
  48. bg-color="#fff">已经到底了</u-divider>
  49. <u-divider color="#B6BDC3" v-else
  50. bg-color="#fff">查询为空</u-divider>
  51. </scroll-view>
  52. </view>
  53. </view>
  54. </u-popup>
  55. </template>
  56. <script>
  57. /**
  58. * picker picker弹出选择器
  59. * @description 此选择器有两种弹出模式:一是时间模式,可以配置年,日,月,时,分,秒参数 二是地区模式,可以配置省,市,区参数
  60. * @tutorial https://www.uviewui.com/components/picker.html
  61. * @property {Object} params 需要显示的参数,见官网说明
  62. * @property {String} mode 模式选择,region-地区类型,time-时间类型(默认time)
  63. * @property {String Number} start-year 可选的开始年份,mode=time时有效(默认1950)
  64. * @property {String Number} end-year 可选的结束年份,mode=time时有效(默认2050)
  65. * @property {Boolean} safe-area-inset-bottom 是否开启底部安全区适配(默认false)
  66. * @property {Boolean} show-time-tag 时间模式时,是否显示后面的年月日中文提示
  67. * @property {String} cancel-color 取消按钮的颜色(默认#606266)
  68. * @property {String} confirm-color 确认按钮的颜色(默认#2979ff)
  69. * @property {String} default-time 默认选中的时间,mode=time时有效
  70. * @property {String} confirm-text 确认按钮的文字
  71. * @property {String} cancel-text 取消按钮的文字
  72. * @property {String} default-region 默认选中的地区,中文形式,mode=region时有效
  73. * @property {String} default-code 默认选中的地区,编号形式,mode=region时有效
  74. * @property {Boolean} mask-close-able 是否允许通过点击遮罩关闭Picker(默认true)
  75. * @property {String Number} z-index 弹出时的z-index值(默认1075)
  76. * @property {Array} default-selector 数组形式,其中每一项表示选择了range对应项中的第几个
  77. * @property {Array} range 自定义选择的数据,mode=selector或mode=multiSelector时有效
  78. * @property {String} range-key 当range参数的元素为对象时,指定Object中的哪个key的值作为选择器显示内容
  79. * @event {Function} confirm 点击确定按钮,返回当前选择的值
  80. * @event {Function} cancel 点击取消按钮,返回当前选择的值
  81. * @example <u-picker v-model="show" mode="time"></u-picker>
  82. */
  83. export default {
  84. name: 'u-picker',
  85. props: {
  86. // picker中需要显示的参数
  87. params: {
  88. type: Object,
  89. default() {
  90. return {
  91. year: true,
  92. month: true,
  93. day: true,
  94. hour: false,
  95. minute: false,
  96. second: false,
  97. province: true,
  98. city: true,
  99. area: true,
  100. timestamp: true,
  101. };
  102. }
  103. },
  104. // 当mode=selector或者mode=multiSelector时,提供的数组
  105. range: {
  106. type: Array,
  107. default() {
  108. return [];
  109. }
  110. },
  111. // 当mode=selector或者mode=multiSelector时,提供的默认选中的下标
  112. defaultSelector: {
  113. type: Array,
  114. default() {
  115. return [0];
  116. }
  117. },
  118. // 当 range 是一个 Array<Object> 时,通过 range-key 来指定 Object 中 key 的值作为选择器显示内容
  119. rangeKey: {
  120. type: String,
  121. default: ''
  122. },
  123. // 模式选择,region-地区类型,time-时间类型,selector-单列模式,multiSelector-多列模式
  124. mode: {
  125. type: String,
  126. default: 'time'
  127. },
  128. // 年份开始时间
  129. startYear: {
  130. type: [String, Number],
  131. default: 1950
  132. },
  133. // 年份结束时间
  134. endYear: {
  135. type: [String, Number],
  136. default: 2050
  137. },
  138. // "取消"按钮的颜色
  139. cancelColor: {
  140. type: String,
  141. default: '#606266'
  142. },
  143. // "确定"按钮的颜色
  144. confirmColor: {
  145. type: String,
  146. default: '#2979ff'
  147. },
  148. // 默认显示的时间,2025-07-02 || 2025-07-02 13:01:00 || 2025/07/02
  149. defaultTime: {
  150. type: String,
  151. default: ''
  152. },
  153. // 默认显示的地区,可传类似["河北省", "秦皇岛市", "北戴河区"]
  154. defaultRegion: {
  155. type: Array,
  156. default() {
  157. return [];
  158. }
  159. },
  160. // 时间模式时,是否显示后面的年月日中文提示
  161. showTimeTag: {
  162. type: Boolean,
  163. default: true
  164. },
  165. // 默认显示地区的编码,defaultRegion和areaCode同时存在,areaCode优先,可传类似["13", "1303", "130304"]
  166. areaCode: {
  167. type: Array,
  168. default() {
  169. return [];
  170. }
  171. },
  172. safeAreaInsetBottom: {
  173. type: Boolean,
  174. default: false
  175. },
  176. // 是否允许通过点击遮罩关闭Picker
  177. maskCloseAble: {
  178. type: Boolean,
  179. default: true
  180. },
  181. // 通过双向绑定控制组件的弹出与收起
  182. value: {
  183. type: Boolean,
  184. default: false
  185. },
  186. // 弹出的z-index值
  187. zIndex: {
  188. type: [String, Number],
  189. default: 0
  190. },
  191. // 顶部标题
  192. title: {
  193. type: String,
  194. default: ''
  195. },
  196. // 取消按钮的文字
  197. cancelText: {
  198. type: String,
  199. default: '取消'
  200. },
  201. // 确认按钮的文字
  202. confirmText: {
  203. type: String,
  204. default: '确认'
  205. }
  206. },
  207. data() {
  208. return {
  209. querykey:'',
  210. years: [],
  211. months: [],
  212. days: [],
  213. hours: [],
  214. minutes: [],
  215. seconds: [],
  216. year: 0,
  217. month: 0,
  218. day: 0,
  219. hour: 0,
  220. minute: 0,
  221. second: 0,
  222. reset: false,
  223. startDate: '',
  224. endDate: '',
  225. valueArr: [],
  226. province: 0,
  227. city: 0,
  228. area: 0,
  229. moving: false // 列是否还在滑动中,微信小程序如果在滑动中就点确定,结果可能不准确
  230. };
  231. },
  232. mounted() {
  233. this.init();
  234. },
  235. computed: {
  236. queryrange(){
  237. var sz=[]
  238. console.log(this.range)
  239. this.range.forEach(item=>{
  240. var k=this.getItemValue(item, 'selector') ;
  241. if(this.querykey==''||k.indexOf(this.querykey)!=-1){
  242. sz.push(item)
  243. }
  244. })
  245. return sz
  246. },
  247. propsChange() {
  248. // 引用这几个变量,是为了监听其变化
  249. return `${this.mode}-${this.defaultTime}-${this.startYear}-${this.endYear}-${this.defaultRegion}-${this.areaCode}`;
  250. },
  251. regionChange() {
  252. // 引用这几个变量,是为了监听其变化
  253. return `${this.province}-${this.city}`;
  254. },
  255. yearAndMonth() {
  256. return `${this.year}-${this.month}`;
  257. },
  258. uZIndex() {
  259. // 如果用户有传递z-index值,优先使用
  260. return this.zIndex ? this.zIndex : this.$u.zIndex.popup;
  261. }
  262. },
  263. watch: {
  264. propsChange() {
  265. this.reset = true;
  266. setTimeout(() => this.init(), 10);
  267. },
  268. // 如果地区发生变化,为了让picker联动起来,必须重置this.citys和this.areas
  269. regionChange(val) {
  270. this.citys = citys[this.province];
  271. this.areas = areas[this.province][this.city];
  272. },
  273. // watch监听月份的变化,实时变更日的天数,因为不同月份,天数不一样
  274. // 一个月可能有30,31天,甚至闰年2月的29天,平年2月28天
  275. yearAndMonth(val) {
  276. if (this.params.year) this.setDays();
  277. },
  278. // 微信和QQ小程序由于一些奇怪的原因(故同时对所有平台均初始化一遍),需要重新初始化才能显示正确的值
  279. value(n) {
  280. if (n) {
  281. this.reset = true;
  282. setTimeout(() => this.init(), 10);
  283. }
  284. }
  285. },
  286. methods: {
  287. // 标识滑动开始,只有微信小程序才有这样的事件
  288. pickstart() {
  289. // #ifdef MP-WEIXIN
  290. this.moving = true;
  291. // #endif
  292. },
  293. // 标识滑动结束
  294. pickend() {
  295. // #ifdef MP-WEIXIN
  296. this.moving = false;
  297. // #endif
  298. },
  299. // 对单列和多列形式的判断是否有传入变量的情况
  300. getItemValue(item, mode) {
  301. // 目前(2020-05-25)uni-app对微信小程序编译有错误,导致v-if为false中的内容也执行,错误导致
  302. // 单列模式或者多列模式中的getItemValue同时被执行,故在这里再加一层判断
  303. if (this.mode == mode) {
  304. return typeof item == 'object' ? item[this.rangeKey] : item;
  305. }
  306. },
  307. // 小于10前面补0,用于月份,日期,时分秒等
  308. formatNumber(num) {
  309. return +num < 10 ? '0' + num : String(num);
  310. },
  311. // 生成递进的数组
  312. generateArray: function(start, end) {
  313. // 转为数值格式,否则用户给end-year等传递字符串值时,下面的end+1会导致字符串拼接,而不是相加
  314. start = Number(start);
  315. end = Number(end);
  316. end = end > start ? end : start;
  317. // 生成数组,获取其中的索引,并剪出来
  318. return [...Array(end + 1).keys()].slice(start);
  319. },
  320. getIndex: function(arr, val) {
  321. let index = arr.indexOf(val);
  322. // 如果index为-1(即找不到index值),~(-1)=-(-1)-1=0,导致条件不成立
  323. return ~index ? index : 0;
  324. },
  325. //日期时间处理
  326. initTimeValue() {
  327. // 格式化时间,在IE浏览器(uni不存在此情况),无法识别日期间的"-"间隔符号
  328. let fdate = this.defaultTime.replace(/\-/g, '/');
  329. fdate = fdate && fdate.indexOf('/') == -1 ? `2020/01/01 ${fdate}` : fdate;
  330. let time = null;
  331. if (fdate) time = new Date(fdate);
  332. else time = new Date();
  333. // 获取年日月时分秒
  334. this.year = time.getFullYear();
  335. this.month = Number(time.getMonth()) + 1;
  336. this.day = time.getDate();
  337. this.hour = time.getHours();
  338. this.minute = time.getMinutes();
  339. this.second = time.getSeconds();
  340. },
  341. init() {
  342. this.valueArr = [];
  343. this.reset = false;
  344. if (this.mode == 'time') {
  345. } else if (this.mode == 'region') {
  346. } else if (this.mode == 'selector') {
  347. this.valueArr = this.defaultSelector;
  348. } else if (this.mode == 'multiSelector') {
  349. this.valueArr = this.defaultSelector;
  350. this.multiSelectorValue = this.defaultSelector;
  351. }
  352. this.$forceUpdate();
  353. },
  354. // 设置picker的某一列值
  355. setYears() {
  356. // 获取年份集合
  357. this.years = this.generateArray(this.startYear, this.endYear);
  358. // 设置this.valueArr某一项的值,是为了让picker预选中某一个值
  359. this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.years, this.year));
  360. },
  361. setMonths() {
  362. this.months = this.generateArray(1, 12);
  363. this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.months, this.month));
  364. },
  365. setDays() {
  366. let totalDays = new Date(this.year, this.month, 0).getDate();
  367. this.days = this.generateArray(1, totalDays);
  368. let index = 0;
  369. // 这里不能使用类似setMonths()中的this.valueArr.splice(this.valueArr.length - 1, xxx)做法
  370. // 因为this.month和this.year变化时,会触发watch中的this.setDays(),导致this.valueArr.length计算有误
  371. if (this.params.year && this.params.month) index = 2;
  372. else if (this.params.month) index = 1;
  373. else if (this.params.year) index = 1;
  374. else index = 0;
  375. // 当月份变化时,会导致日期的天数也会变化,如果原来选的天数大于变化后的天数,则重置为变化后的最大值
  376. // 比如原来选中3月31日,调整为2月后,日期变为最大29,这时如果day值继续为31显然不合理,于是将其置为29(picker-column从1开始)
  377. if(this.day > this.days.length) this.day = this.days.length;
  378. this.valueArr.splice(index, 1, this.getIndex(this.days, this.day));
  379. },
  380. setHours() {
  381. this.hours = this.generateArray(0, 23);
  382. this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.hours, this.hour));
  383. },
  384. setMinutes() {
  385. this.minutes = this.generateArray(0, 59);
  386. this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.minutes, this.minute));
  387. },
  388. setSeconds() {
  389. this.seconds = this.generateArray(0, 59);
  390. this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.seconds, this.second));
  391. },
  392. setProvinces() {
  393. // 判断是否需要province参数
  394. if (!this.params.province) return;
  395. let tmp = '';
  396. let useCode = false;
  397. // 如果同时配置了defaultRegion和areaCode,优先使用areaCode参数
  398. if (this.areaCode.length) {
  399. tmp = this.areaCode[0];
  400. useCode = true;
  401. } else if (this.defaultRegion.length) tmp = this.defaultRegion[0];
  402. else tmp = 0;
  403. // 历遍省份数组匹配
  404. provinces.map((v, k) => {
  405. if (useCode ? v.value == tmp : v.label == tmp) {
  406. tmp = k;
  407. }
  408. });
  409. this.province = tmp;
  410. this.provinces = provinces;
  411. // 设置默认省份的值
  412. this.valueArr.splice(0, 1, this.province);
  413. },
  414. setCitys() {
  415. if (!this.params.city) return;
  416. let tmp = '';
  417. let useCode = false;
  418. if (this.areaCode.length) {
  419. tmp = this.areaCode[1];
  420. useCode = true;
  421. } else if (this.defaultRegion.length) tmp = this.defaultRegion[1];
  422. else tmp = 0;
  423. citys[this.province].map((v, k) => {
  424. if (useCode ? v.value == tmp : v.label == tmp) {
  425. tmp = k;
  426. }
  427. });
  428. this.city = tmp;
  429. this.citys = citys[this.province];
  430. this.valueArr.splice(1, 1, this.city);
  431. },
  432. setAreas() {
  433. if (!this.params.area) return;
  434. let tmp = '';
  435. let useCode = false;
  436. if (this.areaCode.length) {
  437. tmp = this.areaCode[2];
  438. useCode = true;
  439. } else if (this.defaultRegion.length) tmp = this.defaultRegion[2];
  440. else tmp = 0;
  441. areas[this.province][this.city].map((v, k) => {
  442. if (useCode ? v.value == tmp : v.label == tmp) {
  443. tmp = k;
  444. }
  445. });
  446. this.area = tmp;
  447. this.areas = areas[this.province][this.city];
  448. this.valueArr.splice(2, 1, this.area);
  449. },
  450. close() {
  451. this.$emit('input', false);
  452. },
  453. // 用户更改picker的列选项
  454. change(e) {
  455. this.valueArr = e.detail.value;
  456. let i = 0;
  457. if (this.mode == 'time') {
  458. // 这里使用i++,是因为this.valueArr数组的长度是不确定长度的,它根据this.params的值来配置长度
  459. // 进入if规则,i会加1,保证了能获取准确的值
  460. if (this.params.year) this.year = this.years[this.valueArr[i++]];
  461. if (this.params.month) this.month = this.months[this.valueArr[i++]];
  462. if (this.params.day) this.day = this.days[this.valueArr[i++]];
  463. if (this.params.hour) this.hour = this.hours[this.valueArr[i++]];
  464. if (this.params.minute) this.minute = this.minutes[this.valueArr[i++]];
  465. if (this.params.second) this.second = this.seconds[this.valueArr[i++]];
  466. } else if (this.mode == 'region') {
  467. if (this.params.province) this.province = this.valueArr[i++];
  468. if (this.params.city) this.city = this.valueArr[i++];
  469. if (this.params.area) this.area = this.valueArr[i++];
  470. } else if (this.mode == 'multiSelector') {
  471. let index = null;
  472. // 对比前后两个数组,寻找变更的是哪一列,如果某一个元素不同,即可判定该列发生了变化
  473. this.defaultSelector.map((val, idx) => {
  474. if (val != e.detail.value[idx]) index = idx;
  475. });
  476. // 为了让用户对多列变化时,对动态设置其他列的变更
  477. if (index != null) {
  478. this.$emit('columnchange', {
  479. column: index,
  480. index: e.detail.value[index]
  481. });
  482. }
  483. }
  484. },
  485. // 用户点击确定按钮
  486. getResult(event = null) {
  487. // #ifdef MP-WEIXIN
  488. if (this.moving) return;
  489. // #endif
  490. let result = {};
  491. // 只返回用户在this.params中配置了为true的字段
  492. if (this.mode == 'time') {
  493. if (this.params.year) result.year = this.formatNumber(this.year || 0);
  494. if (this.params.month) result.month = this.formatNumber(this.month || 0);
  495. if (this.params.day) result.day = this.formatNumber(this.day || 0);
  496. if (this.params.hour) result.hour = this.formatNumber(this.hour || 0);
  497. if (this.params.minute) result.minute = this.formatNumber(this.minute || 0);
  498. if (this.params.second) result.second = this.formatNumber(this.second || 0);
  499. if (this.params.timestamp) result.timestamp = this.getTimestamp();
  500. } else if (this.mode == 'region') {
  501. if (this.params.province) result.province = provinces[this.province];
  502. if (this.params.city) result.city = citys[this.province][this.city];
  503. if (this.params.area) result.area = areas[this.province][this.city][this.area];
  504. } else if (this.mode == 'selector') {
  505. result = this.valueArr;
  506. } else if (this.mode == 'multiSelector') {
  507. result = this.valueArr;
  508. }
  509. if (event) this.$emit(event, result);
  510. this.close();
  511. },
  512. // 获取时间戳
  513. getTimestamp() {
  514. // yyyy-mm-dd为安卓写法,不支持iOS,需要使用"/"分隔,才能二者兼容
  515. let time = this.year + '/' + this.month + '/' + this.day + ' ' + this.hour + ':' + this.minute + ':' + this.second;
  516. return new Date(time).getTime() / 1000;
  517. }
  518. }
  519. };
  520. </script>
  521. <style lang="scss" scoped>
  522. .u-datetime-picker {
  523. position: relative;
  524. z-index: 999;
  525. }
  526. .u-picker-view {
  527. height: 100%;
  528. box-sizing: border-box;
  529. }
  530. .u-picker-header {
  531. width: 100%;
  532. height: 90rpx;
  533. padding: 0 40rpx;
  534. display: flex;
  535. justify-content: space-between;
  536. align-items: center;
  537. box-sizing: border-box;
  538. font-size: 30rpx;
  539. background: #fff;
  540. position: relative;
  541. }
  542. .u-picker-header::after {
  543. content: '';
  544. position: absolute;
  545. border-bottom: 1rpx solid #eaeef1;
  546. -webkit-transform: scaleY(0.5);
  547. transform: scaleY(0.5);
  548. bottom: 0;
  549. right: 0;
  550. left: 0;
  551. }
  552. .u-picker__title {
  553. color: #606266;
  554. }
  555. .u-picker-body {
  556. width: 100%;
  557. height: 500rpx;
  558. overflow: hidden;
  559. background-color: #fff;
  560. }
  561. .u-column-item {
  562. display: flex;
  563. align-items: center;
  564. justify-content: center;
  565. font-size: 32rpx;
  566. color: #303133;
  567. padding: 0 8rpx;
  568. }
  569. .u-text {
  570. font-size: 24rpx;
  571. padding-left: 8rpx;
  572. }
  573. .u-btn-picker {
  574. padding: 16rpx;
  575. box-sizing: border-box;
  576. text-align: center;
  577. text-decoration: none;
  578. }
  579. .u-opacity {
  580. opacity: 0.5;
  581. }
  582. .u-btn-picker--primary {
  583. color: #2979ff;
  584. }
  585. .u-btn-picker--tips {
  586. color: #909399;
  587. }
  588. .scroll-Y {
  589. height: 600rpx;
  590. }
  591. .u-list-body{
  592. width: 100%;
  593. background-color: #fff;
  594. display: flex;
  595. flex-wrap: wrap;
  596. .u-list-item{
  597. padding: 5px;
  598. margin: 5px;
  599. border: 1px solid #909399;
  600. color:#909399;
  601. }
  602. .list-index{
  603. border: 1px solid #2979ff;
  604. color: #2979ff;
  605. }
  606. }
  607. </style>