index.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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: null,
  71. filter: null,
  72. type: {
  73. type: String,
  74. value: 'datetime'
  75. },
  76. showToolbar: {
  77. type: Boolean,
  78. value: true
  79. },
  80. formatter: {
  81. type: null,
  82. value: defaultFormatter
  83. },
  84. minDate: {
  85. type: Number,
  86. value: new Date(currentYear - 10, 0, 1).getTime()
  87. },
  88. maxDate: {
  89. type: Number,
  90. value: new Date(currentYear + 10, 11, 31).getTime()
  91. },
  92. minHour: {
  93. type: Number,
  94. value: 0
  95. },
  96. maxHour: {
  97. type: Number,
  98. value: 23
  99. },
  100. minMinute: {
  101. type: Number,
  102. value: 0
  103. },
  104. maxMinute: {
  105. type: Number,
  106. value: 59
  107. }
  108. }),
  109. watch: {
  110. value: 'updateValue',
  111. type: 'updateValue',
  112. minDate: 'updateValue',
  113. maxDate: 'updateValue',
  114. minHour: 'updateValue',
  115. maxHour: 'updateValue',
  116. minMinute: 'updateValue',
  117. maxMinute: 'updateValue'
  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. const isDateType = data.type !== 'time';
  217. if (isDateType && !isValidDate(value)) {
  218. value = data.minDate;
  219. } else if (!isDateType && !value) {
  220. const { minHour } = data;
  221. value = `${padZero(minHour)}:00`;
  222. }
  223. if (!isDateType) {
  224. let [hour, minute] = value.split(':');
  225. hour = padZero(range(hour, data.minHour, data.maxHour));
  226. minute = padZero(range(minute, data.minMinute, data.maxMinute));
  227. return `${hour}:${minute}`;
  228. }
  229. value = Math.max(value, data.minDate);
  230. value = Math.min(value, data.maxDate);
  231. return value;
  232. },
  233. getBoundary(type, innerValue) {
  234. const value = new Date(innerValue);
  235. const boundary = new Date(this[`${type}Date`]);
  236. const year = boundary.getFullYear();
  237. let month = 1;
  238. let date = 1;
  239. let hour = 0;
  240. let minute = 0;
  241. if (type === 'max') {
  242. month = 12;
  243. date = getMonthEndDay(value.getFullYear(), value.getMonth() + 1);
  244. hour = 23;
  245. minute = 59;
  246. }
  247. if (value.getFullYear() === year) {
  248. month = boundary.getMonth() + 1;
  249. if (value.getMonth() + 1 === month) {
  250. date = boundary.getDate();
  251. if (value.getDate() === date) {
  252. hour = boundary.getHours();
  253. if (value.getHours() === hour) {
  254. minute = boundary.getMinutes();
  255. }
  256. }
  257. }
  258. }
  259. return {
  260. [`${type}Year`]: year,
  261. [`${type}Month`]: month,
  262. [`${type}Date`]: date,
  263. [`${type}Hour`]: hour,
  264. [`${type}Minute`]: minute
  265. };
  266. },
  267. onCancel() {
  268. this.$emit('cancel');
  269. },
  270. onConfirm() {
  271. this.$emit('confirm', this.innerValue);
  272. },
  273. onChange() {
  274. const { data } = this;
  275. let value;
  276. const picker = this.getPicker();
  277. if (data.type === 'time') {
  278. const indexes = picker.getIndexes();
  279. value = `${+data.columns[0].values[indexes[0]]}:${+data.columns[1].values[indexes[1]]}`;
  280. } else {
  281. const values = picker.getValues();
  282. const year = getTrueValue(values[0]);
  283. const month = getTrueValue(values[1]);
  284. const maxDate = getMonthEndDay(year, month);
  285. let date = getTrueValue(values[2]);
  286. if (data.type === 'year-month') {
  287. date = 1;
  288. }
  289. date = date > maxDate ? maxDate : date;
  290. let hour = 0;
  291. let minute = 0;
  292. if (data.type === 'datetime') {
  293. hour = getTrueValue(values[3]);
  294. minute = getTrueValue(values[4]);
  295. }
  296. value = new Date(year, month - 1, date, hour, minute);
  297. }
  298. value = this.correctValue(value);
  299. this.updateColumnValue(value).then(() => {
  300. this.$emit('input', value);
  301. this.$emit('change', picker);
  302. });
  303. },
  304. updateColumnValue(value) {
  305. let values = [];
  306. const { type, formatter = defaultFormatter } = this;
  307. const picker = this.getPicker();
  308. if (type === 'time') {
  309. const pair = value.split(':');
  310. values = [formatter('hour', pair[0]), formatter('minute', pair[1])];
  311. } else {
  312. const date = new Date(value);
  313. values = [formatter('year', `${date.getFullYear()}`), formatter('month', padZero(date.getMonth() + 1))];
  314. if (type === 'date') {
  315. values.push(formatter('day', padZero(date.getDate())));
  316. }
  317. if (type === 'datetime') {
  318. values.push(formatter('day', padZero(date.getDate())), formatter('hour', padZero(date.getHours())), formatter('minute', padZero(date.getMinutes())));
  319. }
  320. }
  321. return this.set({
  322. innerValue: value
  323. })
  324. .then(() => this.updateColumns())
  325. .then(() => picker.setValues(values));
  326. }
  327. },
  328. created() {
  329. const innerValue = this.correctValue(this.value);
  330. this.updateColumnValue(innerValue).then(() => {
  331. this.$emit('input', innerValue);
  332. });
  333. }
  334. };
  335. </script>
  336. <style>
  337. @import '../common/index.ttss';
  338. </style>