u-picker.vue 19 KB

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