index.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <template>
  2. <view>
  3. <van-picker
  4. class="van-datetime-picker"
  5. active-class="active-class"
  6. toolbar-class="toolbar-class"
  7. column-class="column-class"
  8. :title="title"
  9. :columns="columns"
  10. :item-height="itemHeight"
  11. :show-toolbar="showToolbar"
  12. :visible-item-count="visibleItemCount"
  13. :confirm-button-text="confirmButtonText"
  14. :cancel-button-text="cancelButtonText"
  15. @change="onChange"
  16. @confirm="onConfirm"
  17. @cancel="onCancel"
  18. />
  19. </view>
  20. </template>
  21. <script>
  22. import { VantComponent } from '../common/component';
  23. import { isDef } from '../common/utils';
  24. import { pickerProps } from '../picker/shared';
  25. const currentYear = new Date().getFullYear();
  26. function isValidDate(date) {
  27. return isDef(date) && !isNaN(new Date(date).getTime());
  28. }
  29. function range(num, min, max) {
  30. return Math.min(Math.max(num, min), max);
  31. }
  32. function padZero(val) {
  33. return `00${val}`.slice(-2);
  34. }
  35. function times(n, iteratee) {
  36. let index = -1;
  37. const result = Array(n < 0 ? 0 : n);
  38. while (++index < n) {
  39. result[index] = iteratee(index);
  40. }
  41. return result;
  42. }
  43. function getTrueValue(formattedValue) {
  44. if (!formattedValue) {
  45. return;
  46. }
  47. while (isNaN(parseInt(formattedValue, 10))) {
  48. formattedValue = formattedValue.slice(1);
  49. }
  50. return parseInt(formattedValue, 10);
  51. }
  52. function getMonthEndDay(year, month) {
  53. return 32 - new Date(year, month - 1, 32).getDate();
  54. }
  55. const defaultFormatter = (_, value) => value;
  56. export default {
  57. data() {
  58. return {
  59. innerValue: Date.now(),
  60. columns: [],
  61. title: '',
  62. showToolbar: '',
  63. visibleItemCount: '',
  64. confirmButtonText: '',
  65. cancelButtonText: ''
  66. };
  67. },
  68. classes: ['active-class', 'toolbar-class', 'column-class'],
  69. props: Object.assign(Object.assign({}, pickerProps), {
  70. value: {
  71. type: null,
  72. observer: 'updateValue'
  73. },
  74. filter: null,
  75. type: {
  76. type: String,
  77. value: 'datetime',
  78. observer: 'updateValue'
  79. },
  80. showToolbar: {
  81. type: Boolean,
  82. value: true
  83. },
  84. formatter: {
  85. type: null,
  86. value: defaultFormatter
  87. },
  88. minDate: {
  89. type: Number,
  90. value: new Date(currentYear - 10, 0, 1).getTime(),
  91. observer: 'updateValue'
  92. },
  93. maxDate: {
  94. type: Number,
  95. value: new Date(currentYear + 10, 11, 31).getTime(),
  96. observer: 'updateValue'
  97. },
  98. minHour: {
  99. type: Number,
  100. value: 0,
  101. observer: 'updateValue'
  102. },
  103. maxHour: {
  104. type: Number,
  105. value: 23,
  106. observer: 'updateValue'
  107. },
  108. minMinute: {
  109. type: Number,
  110. value: 0,
  111. observer: 'updateValue'
  112. },
  113. maxMinute: {
  114. type: Number,
  115. value: 59,
  116. observer: 'updateValue'
  117. }
  118. }),
  119. methods: {
  120. updateValue() {
  121. const { data } = this;
  122. const val = this.correctValue(this.value);
  123. const isEqual = val === data.innerValue;
  124. if (!isEqual) {
  125. this.updateColumnValue(val).then(() => {
  126. this.$emit('input', val);
  127. });
  128. } else {
  129. this.updateColumns();
  130. }
  131. },
  132. getPicker() {
  133. if (this.picker == null) {
  134. this.picker = this.zpSelectComponent('.van-datetime-picker');
  135. const { picker } = this;
  136. const { setColumnValues } = picker;
  137. picker.setColumnValues = (...args) => setColumnValues.apply(picker, [...args, false]);
  138. }
  139. return this.picker;
  140. },
  141. updateColumns() {
  142. const { formatter = defaultFormatter } = this;
  143. const results = this.getOriginColumns().map((column) => ({
  144. values: column.values.map((value) => formatter(column.type, value))
  145. }));
  146. return this.set({
  147. columns: results
  148. });
  149. },
  150. getOriginColumns() {
  151. const { filter } = this;
  152. const results = this.getRanges().map(({ type, range }) => {
  153. let values = times(range[1] - range[0] + 1, (index) => {
  154. let value = range[0] + index;
  155. value = type === 'year' ? `${value}` : padZero(value);
  156. return value;
  157. });
  158. if (filter) {
  159. values = filter(type, values);
  160. }
  161. return {
  162. type,
  163. values
  164. };
  165. });
  166. return results;
  167. },
  168. getRanges() {
  169. const { data } = this;
  170. if (data.type === 'time') {
  171. return [
  172. {
  173. type: 'hour',
  174. range: [data.minHour, data.maxHour]
  175. },
  176. {
  177. type: 'minute',
  178. range: [data.minMinute, data.maxMinute]
  179. }
  180. ];
  181. }
  182. const { maxYear, maxDate, maxMonth, maxHour, maxMinute } = this.getBoundary('max', data.innerValue);
  183. const { minYear, minDate, minMonth, minHour, minMinute } = this.getBoundary('min', data.innerValue);
  184. const result = [
  185. {
  186. type: 'year',
  187. range: [minYear, maxYear]
  188. },
  189. {
  190. type: 'month',
  191. range: [minMonth, maxMonth]
  192. },
  193. {
  194. type: 'day',
  195. range: [minDate, maxDate]
  196. },
  197. {
  198. type: 'hour',
  199. range: [minHour, maxHour]
  200. },
  201. {
  202. type: 'minute',
  203. range: [minMinute, maxMinute]
  204. }
  205. ];
  206. if (data.type === 'date') {
  207. result.splice(3, 2);
  208. }
  209. if (data.type === 'year-month') {
  210. result.splice(2, 3);
  211. }
  212. return result;
  213. },
  214. correctValue(value) {
  215. const { data } = this;
  216. // validate value
  217. const isDateType = data.type !== 'time';
  218. if (isDateType && !isValidDate(value)) {
  219. value = data.minDate;
  220. } else if (!isDateType && !value) {
  221. const { minHour } = data;
  222. value = `${padZero(minHour)}:00`;
  223. }
  224. // time type
  225. if (!isDateType) {
  226. let [hour, minute] = value.split(':');
  227. hour = padZero(range(hour, data.minHour, data.maxHour));
  228. minute = padZero(range(minute, data.minMinute, data.maxMinute));
  229. return `${hour}:${minute}`;
  230. }
  231. // date type
  232. value = Math.max(value, data.minDate);
  233. value = Math.min(value, data.maxDate);
  234. return value;
  235. },
  236. getBoundary(type, innerValue) {
  237. const value = new Date(innerValue);
  238. const boundary = new Date(this[`${type}Date`]);
  239. const year = boundary.getFullYear();
  240. let month = 1;
  241. let date = 1;
  242. let hour = 0;
  243. let minute = 0;
  244. if (type === 'max') {
  245. month = 12;
  246. date = getMonthEndDay(value.getFullYear(), value.getMonth() + 1);
  247. hour = 23;
  248. minute = 59;
  249. }
  250. if (value.getFullYear() === year) {
  251. month = boundary.getMonth() + 1;
  252. if (value.getMonth() + 1 === month) {
  253. date = boundary.getDate();
  254. if (value.getDate() === date) {
  255. hour = boundary.getHours();
  256. if (value.getHours() === hour) {
  257. minute = boundary.getMinutes();
  258. }
  259. }
  260. }
  261. }
  262. return {
  263. [`${type}Year`]: year,
  264. [`${type}Month`]: month,
  265. [`${type}Date`]: date,
  266. [`${type}Hour`]: hour,
  267. [`${type}Minute`]: minute
  268. };
  269. },
  270. onCancel() {
  271. this.$emit('cancel');
  272. },
  273. onConfirm() {
  274. this.$emit('confirm', this.innerValue);
  275. },
  276. onChange() {
  277. const { data } = this;
  278. let value;
  279. const picker = this.getPicker();
  280. if (data.type === 'time') {
  281. const indexes = picker.getIndexes();
  282. value = `${+data.columns[0].values[indexes[0]]}:${+data.columns[1].values[indexes[1]]}`;
  283. } else {
  284. const values = picker.getValues();
  285. const year = getTrueValue(values[0]);
  286. const month = getTrueValue(values[1]);
  287. const maxDate = getMonthEndDay(year, month);
  288. let date = getTrueValue(values[2]);
  289. if (data.type === 'year-month') {
  290. date = 1;
  291. }
  292. date = date > maxDate ? maxDate : date;
  293. let hour = 0;
  294. let minute = 0;
  295. if (data.type === 'datetime') {
  296. hour = getTrueValue(values[3]);
  297. minute = getTrueValue(values[4]);
  298. }
  299. value = new Date(year, month - 1, date, hour, minute);
  300. }
  301. value = this.correctValue(value);
  302. this.updateColumnValue(value).then(() => {
  303. this.$emit('input', value);
  304. this.$emit('change', picker);
  305. });
  306. },
  307. updateColumnValue(value) {
  308. let values = [];
  309. const { type, formatter = defaultFormatter } = this;
  310. const picker = this.getPicker();
  311. if (type === 'time') {
  312. const pair = value.split(':');
  313. values = [formatter('hour', pair[0]), formatter('minute', pair[1])];
  314. } else {
  315. const date = new Date(value);
  316. values = [formatter('year', `${date.getFullYear()}`), formatter('month', padZero(date.getMonth() + 1))];
  317. if (type === 'date') {
  318. values.push(formatter('day', padZero(date.getDate())));
  319. }
  320. if (type === 'datetime') {
  321. values.push(formatter('day', padZero(date.getDate())), formatter('hour', padZero(date.getHours())), formatter('minute', padZero(date.getMinutes())));
  322. }
  323. }
  324. return this.set({
  325. innerValue: value
  326. })
  327. .then(() => this.updateColumns())
  328. .then(() => picker.setValues(values));
  329. }
  330. },
  331. created() {
  332. const innerValue = this.correctValue(this.value);
  333. this.updateColumnValue(innerValue).then(() => {
  334. this.$emit('input', innerValue);
  335. });
  336. }
  337. };
  338. </script>
  339. <style>
  340. @import './index.css';
  341. </style>