index.vue 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <template>
  2. <div :class="ui" class="hc-counter-box">
  3. <div class="counter-box">
  4. <div class="counter-btn first" :disabled="modelVal <= 1" @click="moveBtnClick">-</div>
  5. <div class='counter-val w-20'>
  6. <span>{{modelVal}}</span>
  7. <span class="ml-2" v-if="text">{{text}}</span>
  8. </div>
  9. <div class="counter-btn end" @click="addBtnClick">+</div>
  10. </div>
  11. </div>
  12. </template>
  13. <script setup>
  14. import {ref, watch} from "vue";
  15. const props = defineProps({
  16. ui: {
  17. type: String,
  18. default: ''
  19. },
  20. modelValue: {
  21. type: [String,Number],
  22. default: 1
  23. },
  24. text: {
  25. type: String,
  26. default: ''
  27. },
  28. })
  29. //转换
  30. const setModelVal = (value) => {
  31. return parseInt(value || 1 + '');
  32. }
  33. const modelVal = ref(setModelVal(props.modelValue))
  34. //监听
  35. watch(() => props.modelValue, (value) => {
  36. modelVal.value = setModelVal(value)
  37. })
  38. const emit = defineEmits(['update:modelValue','addClick','moveClick'])
  39. //减少
  40. const moveBtnClick = () => {
  41. let val = modelVal.value - 1;
  42. if (val <= 1) {
  43. modelVal.value = 1;
  44. } else {
  45. modelVal.value = val;
  46. emit('update:modelValue', val)
  47. emit('moveClick', val)
  48. }
  49. }
  50. //增加
  51. const addBtnClick = () => {
  52. let val = modelVal.value + 1;
  53. modelVal.value = val;
  54. emit('update:modelValue', val)
  55. emit('addClick', val)
  56. }
  57. </script>
  58. <style lang="scss" scoped>
  59. .hc-counter-box {
  60. position: relative;
  61. display: inline-block;
  62. height: 32px;
  63. .counter-box {
  64. display: flex;
  65. align-items: center;
  66. height: inherit;
  67. color: #000000;
  68. .counter-btn {
  69. height: 32px;
  70. width: 32px;
  71. border: 1px solid #eeeeee;
  72. display: flex;
  73. align-items: center;
  74. justify-content: center;
  75. font-size: 22px;
  76. font-weight: 100;
  77. cursor: pointer;
  78. user-select: none;
  79. background-color: white;
  80. transition: color 0.2s, background-color 0.2s;
  81. &.first {
  82. border-radius: 4px 0 0 4px;
  83. }
  84. &.end {
  85. border-radius: 0 4px 4px 0;
  86. }
  87. &:hover {
  88. color: var(--el-color-primary);
  89. background-color: var(--el-color-primary-light-8);
  90. }
  91. &[disabled=true] {
  92. cursor: not-allowed;
  93. color: #c5c5c5;
  94. background-color: #f3f3f3;
  95. }
  96. }
  97. .counter-val {
  98. height: inherit;
  99. border-top: 1px solid #eeeeee;
  100. border-bottom: 1px solid #eeeeee;
  101. display: flex;
  102. align-items: center;
  103. justify-content: center;
  104. }
  105. }
  106. }
  107. </style>