yearSelect.vue 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <template>
  2. <u-input :value="year" v-if="readonly" readonly></u-input>
  3. <simple-select v-else v-model="year" load-type="local" :data="options" :readonly="readonly" @on-change="changed"></simple-select>
  4. </template>
  5. <script>
  6. import simpleSelect from './simpleSelect.vue';
  7. import { strOrNull } from '@/utils/tools';
  8. export default {
  9. name:"yearSelect",
  10. props: {
  11. value: {
  12. type: [String, Number],
  13. required: false,
  14. default: null,
  15. },
  16. range: {
  17. type: Number,
  18. required: false,
  19. default: 10,
  20. },
  21. readonly: {
  22. type: Boolean,
  23. required: false,
  24. default: false,
  25. }
  26. },
  27. components: {
  28. simpleSelect
  29. },
  30. data() {
  31. return {
  32. year: this.parseValue(this.value),
  33. options: [],
  34. };
  35. },
  36. watch: {
  37. value(n, o) {
  38. this.year = this.parseValue(n)
  39. }
  40. },
  41. mounted() {
  42. this.init()
  43. },
  44. methods: {
  45. init() {
  46. const now = new Date()
  47. const year = now.getFullYear()
  48. for(let i = this.range; i > 0; i --) {
  49. const o = `${year - i}`
  50. this.options.push({
  51. text: o,
  52. value: o,
  53. })
  54. }
  55. this.options.push({
  56. text: year + '',
  57. value: year + '',
  58. })
  59. for(let i = 1; i <= this.range; i ++) {
  60. const o = `${year + i}`
  61. this.options.push({
  62. text: o,
  63. value: o,
  64. })
  65. }
  66. },
  67. parseValue(v) {
  68. let ret = strOrNull(v)
  69. if(typeof v === 'string') {
  70. if(v.includes('-')) {
  71. const [date, time] = v.split(' ')
  72. const [y, ... other] = date.split('-')
  73. ret = strOrNull(y)
  74. }
  75. }
  76. this.appendOptions(ret)
  77. return ret
  78. },
  79. appendOptions(v) {
  80. if(! this.options) return
  81. const n = this.options.find(d => d.value === v)
  82. if(! n) {
  83. this.options = [{
  84. text: v,
  85. value: v,
  86. }, ... this.options]
  87. }
  88. },
  89. changed(n) {
  90. this.year = n
  91. this.$emit('input', strOrNull(this.year))
  92. }
  93. }
  94. }
  95. </script>
  96. <style>
  97. </style>