u-picker.vue 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. <!-- 选择器 -->
  2. <template>
  3. <u-popup
  4. :maskCloseAble="maskCloseAble"
  5. mode="bottom"
  6. :popup="false"
  7. v-model="popupValue"
  8. length="auto"
  9. :safeAreaInsetBottom="safeAreaInsetBottom"
  10. @close="close"
  11. :z-index="uZIndex"
  12. :blur="blur"
  13. >
  14. <view class="u-datetime-picker">
  15. <view class="u-picker-header" @touchmove.stop.prevent="stop">
  16. <view
  17. class="u-btn-picker u-btn-picker--tips"
  18. :style="{ color: cancelColor }"
  19. hover-class="u-opacity"
  20. :hover-stay-time="150"
  21. @click="getResult('cancel')"
  22. >
  23. {{ cancelText }}
  24. </view>
  25. <view class="u-picker__title">{{ title }}</view>
  26. <view
  27. class="u-btn-picker u-btn-picker--primary"
  28. :style="{ color: moving ? cancelColor : confirmColor }"
  29. hover-class="u-opacity"
  30. :hover-stay-time="150"
  31. @touchmove.stop="stop"
  32. @click.stop="getResult('confirm')"
  33. >
  34. {{ confirmText }}
  35. </view>
  36. </view>
  37. <view class="u-picker-body">
  38. <picker-view
  39. v-if="mode == 'region'"
  40. :value="valueArr"
  41. @change="change"
  42. class="u-picker-view"
  43. @pickstart="pickstart"
  44. @pickend="pickend"
  45. >
  46. <picker-view-column v-if="showColumnCom && params && params.province">
  47. <view class="u-column-item" v-for="(item, index) in provinces" :key="index">
  48. <view class="u-line-1">{{ item.name }}</view>
  49. </view>
  50. </picker-view-column>
  51. <picker-view-column v-if="showColumnCom && params && params.city">
  52. <view class="u-column-item" v-for="(item, index) in citys" :key="index">
  53. <view class="u-line-1">{{ item.name }}</view>
  54. </view>
  55. </picker-view-column>
  56. <picker-view-column v-if="showColumnCom && params && params.area">
  57. <view class="u-column-item" v-for="(item, index) in areas" :key="index">
  58. <view class="u-line-1">{{ item.name }}</view>
  59. </view>
  60. </picker-view-column>
  61. </picker-view>
  62. <picker-view
  63. v-else-if="mode == 'time'"
  64. :value="valueArr"
  65. @change="change"
  66. class="u-picker-view"
  67. @pickstart="pickstart"
  68. @pickend="pickend"
  69. >
  70. <picker-view-column v-if="showColumnCom && params && params.year">
  71. <view class="u-column-item" v-for="(item, index) in years" :key="index">
  72. {{ item }}
  73. <text class="u-text" v-if="showTimeTag">年</text>
  74. </view>
  75. </picker-view-column>
  76. <picker-view-column v-if="showColumnCom && params && params.month">
  77. <view class="u-column-item" v-for="(item, index) in months" :key="index">
  78. {{ formatNumber(item) }}
  79. <text class="u-text" v-if="showTimeTag">月</text>
  80. </view>
  81. </picker-view-column>
  82. <picker-view-column v-if="showColumnCom && params && params.day">
  83. <view class="u-column-item" v-for="(item, index) in days" :key="index">
  84. {{ formatNumber(item) }}
  85. <text class="u-text" v-if="showTimeTag">日</text>
  86. </view>
  87. </picker-view-column>
  88. <picker-view-column v-if="showColumnCom && params && params.hour">
  89. <view class="u-column-item" v-for="(item, index) in hours" :key="index">
  90. {{ formatNumber(item) }}
  91. <text class="u-text" v-if="showTimeTag">时</text>
  92. </view>
  93. </picker-view-column>
  94. <picker-view-column v-if="showColumnCom && params && params.minute">
  95. <view class="u-column-item" v-for="(item, index) in minutes" :key="index">
  96. {{ formatNumber(item) }}
  97. <text class="u-text" v-if="showTimeTag">分</text>
  98. </view>
  99. </picker-view-column>
  100. <picker-view-column v-if="showColumnCom && params && params.second">
  101. <view class="u-column-item" v-for="(item, index) in seconds" :key="index">
  102. {{ formatNumber(item) }}
  103. <text class="u-text" v-if="showTimeTag">秒</text>
  104. </view>
  105. </picker-view-column>
  106. </picker-view>
  107. <picker-view
  108. v-else-if="mode == 'selector'"
  109. :value="valueArr"
  110. @change="change"
  111. class="u-picker-view"
  112. @pickstart="pickstart"
  113. @pickend="pickend"
  114. >
  115. <picker-view-column v-if="showColumnCom">
  116. <view class="u-column-item" v-for="(item, index) in range" :key="index">
  117. <view class="u-line-1">{{ getItemValue(item, "selector") }}</view>
  118. </view>
  119. </picker-view-column>
  120. </picker-view>
  121. <picker-view
  122. v-else-if="mode == 'multiSelector'"
  123. :value="valueArr"
  124. @change="change"
  125. class="u-picker-view"
  126. @pickstart="pickstart"
  127. @pickend="pickend"
  128. >
  129. <picker-view-column v-if="showColumnCom" v-for="(item, index) in range" :key="index">
  130. <view class="u-column-item" v-for="(item1, index1) in item" :key="index1">
  131. <view class="u-line-1">{{ getItemValue(item1, "multiSelector") }}</view>
  132. </view>
  133. </picker-view-column>
  134. </picker-view>
  135. </view>
  136. </view>
  137. </u-popup>
  138. </template>
  139. <script>
  140. import provinces from "../../libs/address/provinces.json";
  141. import citys from "../../libs/address/citys.json";
  142. import areas from "../../libs/address/areas.json";
  143. import timeFormat from '../../libs/function/timeFormat.js';
  144. /**
  145. * picker picker弹出选择器
  146. * @description 此选择器有两种弹出模式:一是时间模式,可以配置年,日,月,时,分,秒参数 二是地区模式,可以配置省,市,区参数
  147. * @tutorial https://www.uviewui.com/components/picker.html
  148. * @property {Object} params 需要显示的参数,见官网说明
  149. * @property {String} mode 模式选择,region-地区类型,time-时间类型(默认time)
  150. * @property {String Number} start-year 可选的开始年份,mode=time时有效(默认1950)
  151. * @property {String Number} end-year 可选的结束年份,mode=time时有效(默认2050)
  152. * @property {Boolean} safe-area-inset-bottom 是否开启底部安全区适配(默认false)
  153. * @property {Boolean} show-time-tag 时间模式时,是否显示后面的年月日中文提示
  154. * @property {String} cancel-color 取消按钮的颜色(默认#606266)
  155. * @property {String} confirm-color 确认按钮的颜色(默认#2979ff)
  156. * @property {String} default-time 默认选中的时间,mode=time时有效
  157. * @property {String} confirm-text 确认按钮的文字
  158. * @property {String} cancel-text 取消按钮的文字
  159. * @property {String} default-region 默认选中的地区,中文形式,mode=region时有效
  160. * @property {String} default-code 默认选中的地区,编号形式,mode=region时有效
  161. * @property {Boolean} mask-close-able 是否允许通过点击遮罩关闭Picker(默认true)
  162. * @property {String Number} z-index 弹出时的z-index值(默认1075)
  163. * @property {Array} default-selector 数组形式,其中每一项表示选择了range对应项中的第几个
  164. * @property {Array} range 自定义选择的数据,mode=selector或mode=multiSelector时有效
  165. * @property {String} range-key 当range参数的元素为对象时,指定Object中的哪个key的值作为选择器显示内容
  166. * @event {Function} confirm 点击确定按钮,返回当前选择的值
  167. * @event {Function} cancel 点击取消按钮,返回当前选择的值
  168. * @example <u-picker v-model="show" mode="time"></u-picker>
  169. */
  170. export default {
  171. name: "u-picker",
  172. emits: ["update:modelValue", "input", "confirm", "cancel", "columnchange"],
  173. props: {
  174. // 通过双向绑定控制组件的弹出与收起
  175. value: {
  176. type: Boolean,
  177. default: false
  178. },
  179. modelValue: {
  180. type: Boolean,
  181. default: false
  182. },
  183. // picker中需要显示的参数
  184. params: {
  185. type: [Object, null],
  186. default() {
  187. return {
  188. year: true,
  189. month: true,
  190. day: true,
  191. hour: false,
  192. minute: false,
  193. second: false,
  194. province: true,
  195. city: true,
  196. area: true,
  197. timestamp: true
  198. };
  199. }
  200. },
  201. // 当mode=selector或者mode=multiSelector时,提供的数组
  202. range: {
  203. type: Array,
  204. default() {
  205. return [];
  206. }
  207. },
  208. // 当mode=selector或者mode=multiSelector时,提供的默认选中的下标
  209. defaultSelector: {
  210. type: Array,
  211. default() {
  212. return [0];
  213. }
  214. },
  215. // 当 range 是一个 Array<Object> 时,通过 range-key 来指定 Object 中 key 的值作为选择器显示内容
  216. rangeKey: {
  217. type: String,
  218. default: ""
  219. },
  220. // 模式选择,region-地区类型,time-时间类型,selector-单列模式,multiSelector-多列模式
  221. mode: {
  222. type: String,
  223. default: "time"
  224. },
  225. // 年份开始时间
  226. startYear: {
  227. type: [String, Number],
  228. default: 1950
  229. },
  230. // 年份结束时间
  231. endYear: {
  232. type: [String, Number],
  233. default: 2050
  234. },
  235. // "取消"按钮的颜色
  236. cancelColor: {
  237. type: String,
  238. default: "#606266"
  239. },
  240. // "确定"按钮的颜色
  241. confirmColor: {
  242. type: String,
  243. default: "#2979ff"
  244. },
  245. // 默认显示的时间,2025-07-02 || 2025-07-02 13:01:00 || 2025/07/02
  246. defaultTime: {
  247. type: String,
  248. default: ""
  249. },
  250. // 默认显示的地区,可传类似["河北省", "秦皇岛市", "北戴河区"]
  251. defaultRegion: {
  252. type: [Array, null],
  253. default() {
  254. return [];
  255. }
  256. },
  257. // 时间模式时,是否显示后面的年月日中文提示
  258. showTimeTag: {
  259. type: Boolean,
  260. default: true
  261. },
  262. // 默认显示地区的编码,defaultRegion和areaCode同时存在,areaCode优先,可传类似["13", "1303", "130304"]
  263. areaCode: {
  264. type: [Array, null],
  265. default() {
  266. return [];
  267. }
  268. },
  269. safeAreaInsetBottom: {
  270. type: Boolean,
  271. default: false
  272. },
  273. // 是否允许通过点击遮罩关闭Picker
  274. maskCloseAble: {
  275. type: Boolean,
  276. default: true
  277. },
  278. // 弹出的z-index值
  279. zIndex: {
  280. type: [String, Number],
  281. default: 0
  282. },
  283. // 顶部标题
  284. title: {
  285. type: String,
  286. default: ""
  287. },
  288. // 取消按钮的文字
  289. cancelText: {
  290. type: String,
  291. default: "取消"
  292. },
  293. // 确认按钮的文字
  294. confirmText: {
  295. type: String,
  296. default: "确认"
  297. },
  298. // 遮罩的模糊度
  299. blur: {
  300. type: [String, Number],
  301. default: 0
  302. }
  303. },
  304. data() {
  305. return {
  306. popupValue: false,
  307. years: [],
  308. months: [],
  309. days: [],
  310. hours: [],
  311. minutes: [],
  312. seconds: [],
  313. year: 0,
  314. month: 0,
  315. day: 0,
  316. hour: 0,
  317. minute: 0,
  318. second: 0,
  319. reset: false,
  320. startDate: "",
  321. endDate: "",
  322. valueArr: [],
  323. provinces: provinces,
  324. citys: citys[0],
  325. areas: areas[0][0],
  326. province: 0,
  327. city: 0,
  328. area: 0,
  329. moving: false // 列是否还在滑动中,微信小程序如果在滑动中就点确定,结果可能不准确
  330. };
  331. },
  332. mounted() {
  333. this.init();
  334. },
  335. computed: {
  336. valueCom() {
  337. // #ifdef VUE2
  338. return this.value;
  339. // #endif
  340. // #ifdef VUE3
  341. return this.modelValue;
  342. // #endif
  343. },
  344. propsChange() {
  345. // 引用这几个变量,是为了监听其变化
  346. let { mode, defaultTime, startYear, endYear, defaultRegion, areaCode, defaultSelector } = this;
  347. return JSON.stringify({ mode, defaultTime, startYear, endYear, defaultRegion, areaCode, defaultSelector });
  348. },
  349. regionChange() {
  350. // 引用这几个变量,是为了监听其变化
  351. return `${this.province}-${this.city}`;
  352. },
  353. yearAndMonth() {
  354. return `${this.year}-${this.month}`;
  355. },
  356. uZIndex() {
  357. // 如果用户有传递z-index值,优先使用
  358. return this.zIndex ? this.zIndex : this.$u.zIndex.popup;
  359. },
  360. // 用来兼容小程序、App、h5
  361. showColumnCom(){
  362. // #ifdef MP
  363. return !this.reset;
  364. // #endif
  365. // #ifndef MP
  366. return true;
  367. // #endif
  368. }
  369. },
  370. watch: {
  371. propsChange() {
  372. this.reset = true;
  373. setTimeout(() => this.init(), 10);
  374. },
  375. // 如果地区发生变化,为了让picker联动起来,必须重置this.citys和this.areas
  376. regionChange(val) {
  377. this.citys = citys[this.province];
  378. this.areas = areas[this.province][this.city];
  379. },
  380. // watch监听月份的变化,实时变更日的天数,因为不同月份,天数不一样
  381. // 一个月可能有30,31天,甚至闰年2月的29天,平年2月28天
  382. yearAndMonth(val) {
  383. if (this.params && this.params.year) this.setDays();
  384. },
  385. // 微信和QQ小程序由于一些奇怪的原因(故同时对所有平台均初始化一遍),需要重新初始化才能显示正确的值
  386. valueCom:{
  387. immediate: true,
  388. handler(n){
  389. if (n) {
  390. this.reset = true;
  391. setTimeout(() => this.init(), 10);
  392. }
  393. this.popupValue = n;
  394. }
  395. }
  396. },
  397. methods: {
  398. // 标识滑动开始,只有微信小程序才有这样的事件
  399. pickstart() {
  400. // #ifdef MP-WEIXIN
  401. this.moving = true;
  402. // #endif
  403. },
  404. // 标识滑动结束
  405. pickend() {
  406. // #ifdef MP-WEIXIN
  407. this.moving = false;
  408. // #endif
  409. },
  410. // 对单列和多列形式的判断是否有传入变量的情况
  411. getItemValue(item, mode) {
  412. // 目前(2020-05-25)uni-app对微信小程序编译有错误,导致v-if为false中的内容也执行,错误导致
  413. // 单列模式或者多列模式中的getItemValue同时被执行,故在这里再加一层判断
  414. if (this.mode == mode) {
  415. return typeof item == "object" ? item[this.rangeKey] : item;
  416. }
  417. },
  418. // 小于10前面补0,用于月份,日期,时分秒等
  419. formatNumber(num) {
  420. return +num < 10 ? "0" + num : String(num);
  421. },
  422. // 生成递进的数组
  423. generateArray: function(start, end) {
  424. // 转为数值格式,否则用户给end-year等传递字符串值时,下面的end+1会导致字符串拼接,而不是相加
  425. start = Number(start);
  426. end = Number(end);
  427. end = end > start ? end : start;
  428. // 生成数组,获取其中的索引,并剪出来
  429. return [...Array(end + 1).keys()].slice(start);
  430. },
  431. getIndex: function(arr, val) {
  432. let index = arr.indexOf(val);
  433. // 如果index为-1(即找不到index值),~(-1)=-(-1)-1=0,导致条件不成立
  434. return ~index ? index : 0;
  435. },
  436. //日期时间处理
  437. initTimeValue() {
  438. // 格式化时间,在IE浏览器(uni不存在此情况),无法识别日期间的"-"间隔符号
  439. let fdate = this.defaultTime.replace(/\-/g, "/");
  440. // 如果未设置默认时间,则默认时间 = 当前时间
  441. if (!this.defaultTime) {
  442. fdate = timeFormat(Date.now(), "yyyy/mm/dd hh:MM:ss");
  443. }
  444. fdate = fdate && fdate.indexOf("/") == -1 ? `2020/01/01 ${fdate}` : fdate;
  445. // 时间字符串处理开始-----------------------------------------------------------
  446. // ios对时间格式有严格要求,2020/01 这样的格式无法正常转时间,必须是2020/01/01 00:00:00 这样的格式
  447. let arr1 = fdate.split(" ");
  448. let arr1_1 = arr1[0] || "";
  449. let arr1_2 = arr1[1] || "";
  450. let arr2;
  451. if (arr1_1.indexOf("-") > -1) {
  452. arr2 = arr1_1.split("-");
  453. } else {
  454. arr2 = arr1_1.split("/");
  455. }
  456. let arr3 = arr1_2.split(":");
  457. let dateObj = {
  458. year: Number(arr2[0]),
  459. month: Number(arr2[1]) || 1,
  460. day: Number(arr2[2]) || 1,
  461. hour: Number(arr3[0]) || 0,
  462. minute: Number(arr3[1]) || 0,
  463. second: Number(arr3[2]) || 0,
  464. };
  465. for (let key in dateObj) {
  466. if (dateObj[key] >= 0 && dateObj[key] < 10) dateObj[key] = `0${dateObj[key]}`;
  467. }
  468. fdate = `${dateObj.year}/${dateObj.month}/${dateObj.day} ${dateObj.hour}:${dateObj.minute}:${dateObj.second}`;
  469. // 时间字符串处理结束-----------------------------------------------------------
  470. let time = null;
  471. if (fdate) time = new Date(fdate);
  472. else time = new Date();
  473. // 获取年日月时分秒
  474. this.year = time.getFullYear();
  475. this.month = Number(time.getMonth()) + 1;
  476. this.day = time.getDate();
  477. this.hour = time.getHours();
  478. this.minute = time.getMinutes();
  479. this.second = time.getSeconds();
  480. },
  481. init() {
  482. this.valueArr = [];
  483. this.reset = false;
  484. let params = this.params || {};
  485. if (this.mode == "time") {
  486. this.initTimeValue();
  487. if (params.year) {
  488. this.valueArr.push(0);
  489. this.setYears();
  490. }
  491. if (params.month) {
  492. this.valueArr.push(0);
  493. this.setMonths();
  494. }
  495. if (params.day) {
  496. this.valueArr.push(0);
  497. this.setDays();
  498. }
  499. if (params.hour) {
  500. this.valueArr.push(0);
  501. this.setHours();
  502. }
  503. if (params.minute) {
  504. this.valueArr.push(0);
  505. this.setMinutes();
  506. }
  507. if (params.second) {
  508. this.valueArr.push(0);
  509. this.setSeconds();
  510. }
  511. } else if (this.mode == "region") {
  512. if (params.province) {
  513. this.valueArr.push(0);
  514. this.setProvinces();
  515. }
  516. if (params.city) {
  517. this.valueArr.push(0);
  518. this.setCitys();
  519. }
  520. if (params.area) {
  521. this.valueArr.push(0);
  522. this.setAreas();
  523. }
  524. } else if (this.mode == "selector") {
  525. this.valueArr = this.defaultSelector;
  526. } else if (this.mode == "multiSelector") {
  527. this.valueArr = this.defaultSelector;
  528. this.multiSelectorValue = this.defaultSelector;
  529. }
  530. this.$forceUpdate();
  531. },
  532. // 设置picker的某一列值
  533. setYears() {
  534. // 获取年份集合
  535. this.years = this.generateArray(this.startYear, this.endYear);
  536. // 设置this.valueArr某一项的值,是为了让picker预选中某一个值
  537. this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.years, this.year));
  538. },
  539. setMonths() {
  540. this.months = this.generateArray(1, 12);
  541. this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.months, this.month));
  542. },
  543. setDays() {
  544. let params = this.params || {};
  545. let totalDays = new Date(this.year, this.month, 0).getDate();
  546. this.days = this.generateArray(1, totalDays);
  547. let index = 0;
  548. // 这里不能使用类似setMonths()中的this.valueArr.splice(this.valueArr.length - 1, xxx)做法
  549. // 因为this.month和this.year变化时,会触发watch中的this.setDays(),导致this.valueArr.length计算有误
  550. if (params.year && params.month) index = 2;
  551. else if (params.month) index = 1;
  552. else if (params.year) index = 1;
  553. else index = 0;
  554. // 当月份变化时,会导致日期的天数也会变化,如果原来选的天数大于变化后的天数,则重置为变化后的最大值
  555. // 比如原来选中3月31日,调整为2月后,日期变为最大29,这时如果day值继续为31显然不合理,于是将其置为29(picker-column从1开始)
  556. if (this.day > this.days.length) this.day = this.days.length;
  557. this.valueArr.splice(index, 1, this.getIndex(this.days, this.day));
  558. },
  559. setHours() {
  560. this.hours = this.generateArray(0, 23);
  561. this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.hours, this.hour));
  562. },
  563. setMinutes() {
  564. this.minutes = this.generateArray(0, 59);
  565. this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.minutes, this.minute));
  566. },
  567. setSeconds() {
  568. this.seconds = this.generateArray(0, 59);
  569. this.valueArr.splice(this.valueArr.length - 1, 1, this.getIndex(this.seconds, this.second));
  570. },
  571. setProvinces() {
  572. let params = this.params || {};
  573. // 判断是否需要province参数
  574. if (!params.province) return;
  575. let tmp = "";
  576. let useCode = false;
  577. // 如果同时配置了defaultRegion和areaCode,优先使用areaCode参数
  578. if (this.areaCode && this.areaCode.length) {
  579. tmp = this.areaCode[0];
  580. useCode = true;
  581. } else if (this.defaultRegion && this.defaultRegion.length) tmp = this.defaultRegion[0];
  582. else tmp = 0;
  583. // 历遍省份数组匹配
  584. provinces.map((v, k) => {
  585. if (useCode ? v.code == tmp : v.name == tmp) {
  586. tmp = k;
  587. }
  588. });
  589. this.province = tmp;
  590. this.provinces = provinces;
  591. // 设置默认省份的值
  592. this.valueArr.splice(0, 1, this.province);
  593. },
  594. setCitys() {
  595. let params = this.params || {};
  596. if (!params.city) return;
  597. let tmp = "";
  598. let useCode = false;
  599. if (this.areaCode && this.areaCode.length) {
  600. tmp = this.areaCode[1];
  601. useCode = true;
  602. } else if (this.defaultRegion && this.defaultRegion.length) tmp = this.defaultRegion[1];
  603. else tmp = 0;
  604. citys[this.province].map((v, k) => {
  605. if (useCode ? v.code == tmp : v.name == tmp) {
  606. tmp = k;
  607. }
  608. });
  609. this.city = tmp;
  610. this.citys = citys[this.province];
  611. this.valueArr.splice(1, 1, this.city);
  612. },
  613. setAreas() {
  614. let params = this.params || {};
  615. if (!params.area) return;
  616. let tmp = "";
  617. let useCode = false;
  618. if (this.areaCode && this.areaCode.length) {
  619. tmp = this.areaCode[2];
  620. useCode = true;
  621. } else if (this.defaultRegion && this.defaultRegion.length) tmp = this.defaultRegion[2];
  622. else tmp = 0;
  623. areas[this.province][this.city].map((v, k) => {
  624. if (useCode ? v.code == tmp : v.name == tmp) {
  625. tmp = k;
  626. }
  627. });
  628. this.area = tmp;
  629. this.areas = areas[this.province][this.city];
  630. this.valueArr.splice(2, 1, this.area);
  631. },
  632. close() {
  633. this.$emit("input", false);
  634. this.$emit("update:modelValue", false);
  635. },
  636. // 用户更改picker的列选项
  637. change(e) {
  638. let params = this.params || {};
  639. let oldValueArr = JSON.parse(JSON.stringify(this.valueArr || []));
  640. this.valueArr = e.detail.value;
  641. let i = 0;
  642. if (this.mode == "time") {
  643. // 这里使用i++,是因为this.valueArr数组的长度是不确定长度的,它根据params的值来配置长度
  644. // 进入if规则,i会加1,保证了能获取准确的值
  645. if (params.year) this.year = this.years[this.valueArr[i++]];
  646. if (params.month) this.month = this.months[this.valueArr[i++]];
  647. if (params.day) this.day = this.days[this.valueArr[i++]];
  648. if (params.hour) this.hour = this.hours[this.valueArr[i++]];
  649. if (params.minute) this.minute = this.minutes[this.valueArr[i++]];
  650. if (params.second) this.second = this.seconds[this.valueArr[i++]];
  651. } else if (this.mode == "region") {
  652. if (params.province) this.province = this.valueArr[i++];
  653. if (params.city) this.city = this.valueArr[i++];
  654. if (params.area) this.area = this.valueArr[i++];
  655. } else if (this.mode == "multiSelector") {
  656. let index = null;
  657. // 对比前后两个数组,寻找变更的是哪一列,如果某一个元素不同,即可判定该列发生了变化
  658. oldValueArr.map((val, idx) => {
  659. if (val !== e.detail.value[idx]) index = idx;
  660. });
  661. // 为了让用户对多列变化时,对动态设置其他列的变更
  662. if (index !== null) {
  663. this.$emit("columnchange", {
  664. column: index,
  665. index: e.detail.value[index]
  666. });
  667. }
  668. }
  669. },
  670. // 用户点击确定按钮
  671. getResult(event = null) {
  672. let params = this.params || {};
  673. // #ifdef MP-WEIXIN
  674. if (this.moving) return;
  675. // #endif
  676. let result = {};
  677. // 只返回用户在params中配置了为true的字段
  678. if (this.mode == "time") {
  679. if (params.year) result.year = this.formatNumber(this.year || 0);
  680. if (params.month) result.month = this.formatNumber(this.month || 0);
  681. if (params.day) result.day = this.formatNumber(this.day || 0);
  682. if (params.hour) result.hour = this.formatNumber(this.hour || 0);
  683. if (params.minute) result.minute = this.formatNumber(this.minute || 0);
  684. if (params.second) result.second = this.formatNumber(this.second || 0);
  685. if (params.timestamp) result.timestamp = this.getTimestamp();
  686. } else if (this.mode == "region") {
  687. if (params.province) result.province = provinces[this.province];
  688. if (params.city) result.city = citys[this.province][this.city];
  689. if (params.area) result.area = areas[this.province][this.city][this.area];
  690. } else if (this.mode == "selector") {
  691. result = this.valueArr;
  692. } else if (this.mode == "multiSelector") {
  693. result = this.valueArr;
  694. }
  695. if (event) this.$emit(event, result);
  696. this.close();
  697. },
  698. // 获取时间戳
  699. getTimestamp() {
  700. // yyyy-mm-dd为安卓写法,不支持iOS,需要使用"/"分隔,才能二者兼容
  701. let time =
  702. this.year +
  703. "/" +
  704. this.month +
  705. "/" +
  706. this.day +
  707. " " +
  708. this.hour +
  709. ":" +
  710. this.minute +
  711. ":" +
  712. this.second;
  713. return new Date(time).getTime() / 1000;
  714. },
  715. // 获得数据源
  716. getDateSource() {
  717. return {
  718. provinces,
  719. citys,
  720. areas
  721. };
  722. },
  723. // 智能识别省市区
  724. regionDiscern(addressText){
  725. // 街道地址
  726. let address = "";
  727. // 省
  728. let province = {};
  729. // 市
  730. let city = {};
  731. // 区
  732. let area = {};
  733. if (!addressText) return { code: -1, msg: "地址文本不能为空" };
  734. addressText.trim(); // 去除前后空格
  735. // 省
  736. // 1.先找出省份,通过匹配前面两个字(中国34个省份中,前面两个字不会重复)
  737. let firstTwoKey = addressText.substring(0, 2); //字符串开始的两个字符
  738. // 所在省的下标
  739. let provinceIndex = -1;
  740. for (let i = 0; i < provinces.length; i++) {
  741. let { code, name } = provinces[i];
  742. if (name.indexOf(firstTwoKey) == 0) {
  743. province = { code, name };
  744. provinceIndex = i;
  745. break;
  746. }
  747. }
  748. if (provinceIndex == -1) return { code: -1, msg: `省份【${firstTwoKey}】没有找到,请输入正确的地址` };
  749. // 获取市
  750. let citysArr = citys[provinceIndex];
  751. // 所在市的下标
  752. let cityIndex = -1;
  753. for (let i = 0; i < citysArr.length; i++) {
  754. let { name, code } = citysArr[i];
  755. // 除去最后一个 市 字
  756. let cityName = name.substr(0, name.length - 1);
  757. // 用城市的名字去匹配 addressText 地址
  758. if (addressText.indexOf(cityName) > -1) {
  759. city = { code, name };
  760. cityIndex = i;
  761. break;
  762. }
  763. }
  764. if (cityIndex == -1) return { code: -1, msg: `地级市没有找到,请输入正确的地址` };
  765. // 区
  766. let areasArr = areas[provinceIndex][cityIndex];
  767. // 所在区的下标
  768. let areaIndex = -1;
  769. for (let i = 0; i < areasArr.length; i++) {
  770. let { code, name } = areasArr[i];
  771. // 区名(县名)一般为3个字,如江干区,有可能会简写成 江干
  772. // 区名(县名)为2个字时,不会简写,如蓉县
  773. let reg = name;
  774. if (name.length > 2) reg += `|${name.substr(0, name.length - 1)}`;
  775. // 查找地址中是否存在该区名
  776. let areaRegExp = new RegExp(reg);
  777. if (addressText.search(areaRegExp) > -1) {
  778. area = { code, name };
  779. // 详情地址
  780. address = addressText.replace(new RegExp(reg), "{{~}}").split("{{~}}")[1];
  781. areaIndex = i;
  782. break;
  783. }
  784. }
  785. if (areaIndex == -1) return { code: -1, msg: "县级市没有找到,请输入正确的地址" };
  786. let formatted_address = `${province.name}${city.name}${area.name}${address}`;
  787. let res = {
  788. code: 0,
  789. msg: "ok",
  790. data: {
  791. province, // 省
  792. city, // 市
  793. area, // 区
  794. address, // 街道地址
  795. formatted_address, // 完整格式化地址
  796. }
  797. };
  798. return res;
  799. },
  800. // 智能识别收货信息
  801. addressDiscern(text) {
  802. // 收货人姓名
  803. let name = "";
  804. // 收货人手机
  805. let mobile = "";
  806. // 街道地址
  807. let address = "";
  808. // 省
  809. let province = {};
  810. // 市
  811. let city = {};
  812. // 区
  813. let area = {};
  814. if (!text) return { code: -1, msg: "地址文本不能为空" };
  815. //let newText = text.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5\ ]/g,' ');
  816. let textArr = text.split(/[^\u4e00-\u9fa5a-zA-Z0-9+-()()]+/g).filter(v => v.length);
  817. if (textArr.length != 3) return { code: -1, msg: "地址格式不正确,请按姓名 手机号 收货地址格式。" };
  818. // 获取姓名和手机号
  819. let temp;
  820. let addressText; // 地址原文
  821. for (let [k, v] of textArr.entries()) {
  822. if (/^1[3,4,5,6,7,8,9][0-9]{9}$/.test(v)) {
  823. mobile = v;
  824. continue;
  825. }
  826. //记录第一次出现的字符串
  827. if (!temp) {
  828. temp = v;
  829. continue;
  830. }
  831. // 当前字符串的长度和之前字符串的长度的对比,进而确定姓名和地址信息
  832. temp.length > v.length? ((addressText = temp), (name = v)): ((addressText = v), (name = temp));
  833. }
  834. let positionRes = this.regionDiscern(addressText);
  835. if (positionRes.code !== 0) return positionRes;
  836. let res = {
  837. code: 0,
  838. msg: "ok",
  839. data: {
  840. name, // 姓名
  841. mobile, // 手机号
  842. position: positionRes.data, // 省市区街道信息
  843. }
  844. };
  845. return res;
  846. },
  847. stop(){
  848. }
  849. }
  850. };
  851. </script>
  852. <style lang="scss" scoped>
  853. .u-datetime-picker {
  854. position: relative;
  855. z-index: 999;
  856. }
  857. .u-picker-view {
  858. height: 100%;
  859. box-sizing: border-box;
  860. }
  861. .u-picker-header {
  862. width: 100%;
  863. height: 90rpx;
  864. padding: 0 40rpx;
  865. display: flex;
  866. justify-content: space-between;
  867. align-items: center;
  868. box-sizing: border-box;
  869. font-size: 30rpx;
  870. background: #fff;
  871. position: relative;
  872. }
  873. .u-picker-header::after {
  874. content: "";
  875. position: absolute;
  876. border-bottom: 1rpx solid #eaeef1;
  877. -webkit-transform: scaleY(0.5);
  878. transform: scaleY(0.5);
  879. bottom: 0;
  880. right: 0;
  881. left: 0;
  882. }
  883. .u-picker__title {
  884. color: $u-content-color;
  885. }
  886. .u-picker-body {
  887. width: 100%;
  888. height: 500rpx;
  889. overflow: hidden;
  890. background-color: #fff;
  891. }
  892. .u-column-item {
  893. display: flex;
  894. align-items: center;
  895. justify-content: center;
  896. font-size: 32rpx;
  897. color: $u-main-color;
  898. padding: 0 8rpx;
  899. }
  900. .u-text {
  901. font-size: 24rpx;
  902. padding-left: 8rpx;
  903. }
  904. .u-btn-picker {
  905. padding: 16rpx;
  906. box-sizing: border-box;
  907. text-align: center;
  908. text-decoration: none;
  909. }
  910. .u-opacity {
  911. opacity: 0.5;
  912. }
  913. .u-btn-picker--primary {
  914. color: $u-type-primary;
  915. }
  916. .u-btn-picker--tips {
  917. color: $u-tips-color;
  918. }
  919. </style>