1
0

index.vue 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <script>
  2. import { defineComponent, h, onMounted, watch } from "vue";
  3. export default defineComponent({
  4. name: "ButtonGroup",
  5. props: {
  6. defaultValue: {
  7. type: Number,
  8. default: 0,
  9. },
  10. },
  11. components: {},
  12. emits: ["change"],
  13. setup(props, ctx) {
  14. const children = ctx.slots
  15. .default()
  16. .filter((item) => item.componentOptions?.tag === "button-group-item");
  17. watch(
  18. () => props.defaultValue,
  19. () => {
  20. setCheckedState(props.defaultValue);
  21. }
  22. );
  23. function setCheckedState(setIndex) {
  24. children.forEach((node, index) => {
  25. if (setIndex !== index) {
  26. node.componentInstance.uncheck();
  27. } else {
  28. node.componentInstance.check();
  29. }
  30. });
  31. }
  32. children.forEach((node, index) => {
  33. const listeners = node.componentOptions.listeners || {};
  34. listeners["click"] = function clickItem() {
  35. setCheckedState(index);
  36. ctx.emit("change", index);
  37. };
  38. node.componentOptions.listeners = listeners;
  39. });
  40. onMounted(() => {
  41. setCheckedState(props.defaultValue);
  42. });
  43. return () =>
  44. h(
  45. "div",
  46. {
  47. class: "button-group",
  48. },
  49. children
  50. );
  51. },
  52. });
  53. </script>
  54. <style scoped lang="less">
  55. .button-group {
  56. display: flex;
  57. }
  58. </style>