index.vue 11KB

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