1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- <script>
- import { defineComponent, h, onMounted, watch } from "vue";
- export default defineComponent({
- name: "ButtonGroup",
- props: {
- defaultValue: {
- type: Number,
- default: 0,
- },
- },
- components: {},
- emits: ["change"],
- setup(props, ctx) {
- const children = ctx.slots
- .default()
- .filter((item) => item.componentOptions?.tag === "button-group-item");
- watch(
- () => props.defaultValue,
- () => {
- setCheckedState(props.defaultValue);
- }
- );
- function setCheckedState(setIndex) {
- children.forEach((node, index) => {
- if (setIndex !== index) {
- node.componentInstance.uncheck();
- } else {
- node.componentInstance.check();
- }
- });
- }
- children.forEach((node, index) => {
- const listeners = node.componentOptions.listeners || {};
- listeners["click"] = function clickItem() {
- setCheckedState(index);
- ctx.emit("change", index);
- };
- node.componentOptions.listeners = listeners;
- });
- onMounted(() => {
- setCheckedState(props.defaultValue);
- });
- return () =>
- h(
- "div",
- {
- class: "button-group",
- },
- children
- );
- },
- });
- </script>
- <style scoped lang="less">
- .button-group {
- display: flex;
- }
- </style>
|