u-picker.vue 19 KB

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