index.vue 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <script>
  2. import { defineComponent, h, onMounted } 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. function setCheckedState(setIndex) {
  18. children.forEach((node, index) => {
  19. if (setIndex !== index) {
  20. node.componentInstance.uncheck();
  21. } else {
  22. node.componentInstance.check();
  23. }
  24. });
  25. }
  26. children.forEach((node, index) => {
  27. const listeners = node.componentOptions.listeners || {};
  28. listeners["click"] = function clickItem() {
  29. setCheckedState(index);
  30. ctx.emit("change", index);
  31. };
  32. node.componentOptions.listeners = listeners;
  33. });
  34. onMounted(() => {
  35. setCheckedState(props.defaultValue);
  36. });
  37. return () =>
  38. h(
  39. "div",
  40. {
  41. class: "button-group",
  42. },
  43. children
  44. );
  45. },
  46. });
  47. </script>
  48. <style scoped lang="less">
  49. .button-group {
  50. display: flex;
  51. }
  52. </style>