index.vue 11KB

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