com-picker.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <style>
  2. .com-picker > div {
  3. float: left;
  4. }
  5. .com-picker:after {
  6. clear: both;
  7. display: block;
  8. content: " ";
  9. }
  10. </style>
  11. <template id="com-picker">
  12. <div class="com-picker">
  13. <div style="display: inline-block">
  14. <slot name="before"></slot>
  15. </div>
  16. <template v-for="(props, index) in reversedList">
  17. <div style="display: inline-block" @click="rowClick(props)">
  18. <slot :props="props"></slot>
  19. </div>
  20. </template>
  21. <slot name="after"></slot>
  22. </div>
  23. </template>
  24. <script>
  25. Vue.component('com-picker', {
  26. template: '#com-picker',
  27. props: {
  28. list: Array,
  29. multiple: Boolean,
  30. max: Number,
  31. },
  32. data() {
  33. return {
  34. checkedList: [],
  35. reversedList: [],
  36. };
  37. },
  38. watch: {
  39. list: function (newList, oldList) {
  40. this.reversedList = [];
  41. for (let i in newList) {
  42. this.reversedList.push({
  43. id: randomString(),
  44. checked: false,
  45. row: newList[i],
  46. });
  47. }
  48. }
  49. },
  50. created() {
  51. },
  52. methods: {
  53. rowClick(props) {
  54. if (this.multiple === true) {
  55. // 多选
  56. if (typeof this.max === 'number' && !props.checked && this.checkedList.length >= this.max) {
  57. // 数量限定
  58. return false;
  59. }
  60. props.checked = !(props.checked);
  61. for (let i in this.checkedList) {
  62. if (this.checkedList[i].id === props.id) {
  63. this.checkedList.splice(i, 1);
  64. break;
  65. }
  66. }
  67. if (props.checked) {
  68. this.checkedList.push(props);
  69. }
  70. } else {
  71. // 单选
  72. for (let i in this.reversedList) {
  73. this.reversedList[i].checked = false;
  74. }
  75. props.checked = !(props.checked);
  76. this.checkedList = [];
  77. if (props.checked === true) {
  78. this.checkedList.push(props);
  79. }
  80. }
  81. let newList = [];
  82. for (let i in this.checkedList) {
  83. newList.push(this.checkedList[i].row);
  84. }
  85. this.$emit('change', newList);
  86. },
  87. },
  88. });
  89. </script>