帮我看下子组件更细了checklist后父组件的数据为什么渲染不出来<template> <div> <div>封装后的多选框</div> <div> <w-checkbox-group v-model:value="checkedList" :options="plainOptions"> </w-checkbox-group> </div> </div> </template> <script lang="ts"> import WCheckboxGroup from "@/components/w-checkbox-group/checkboxGroup.vue"; import { defineComponent, reactive, toRefs, ref, onUpdated } from "vue"; const plainOptions = [ { label: "Apple", value: "Apple" }, { label: "Pear", value: "Pear" }, { label: "cc", value: "cc" }, ]; export default defineComponent({ components: { WCheckboxGroup, }, setup() { const state = reactive({ indeterminate: true, checkAll: false, checkedList: ["Apple"], }); const onChangeOption = (val: any) => { // const v = val.find((item: any) => !state.checkedList.includes(item)); // state.checkedList = [v]; }; return { ...toRefs(state), plainOptions, onChangeOption, }; }, }); </script>
时间: 2023-06-17 17:08:36 浏览: 165
看起来你的代码中没有使用 `onChangeOption` 方法,所以父组件的数据不会更新。你可以在 `WCheckboxGroup` 子组件中触发 `onChangeOption` 方法来更新父组件的数据。
你可以在 `WCheckboxGroup` 组件中添加一个 `watch` 监听 `value` 的变化,并在变化时触发 `onChangeOption` 方法。修改后的代码如下:
```vue
<template>
<div>
<div v-for="(option, index) in options" :key="index">
<label>
<input type="checkbox" v-model="option.checked" :value="option.value" @change="onChange" />
{{ option.label }}
</label>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, toRefs, watch } from "vue";
export default defineComponent({
name: "WCheckboxGroup",
props: {
value: {
type: Array,
default: () => [],
},
options: {
type: Array,
default: () => [],
},
},
setup(props, { emit }) {
const onChange = (event: Event) => {
const target = event.target as HTMLInputElement;
const value = target.value;
const checked = target.checked;
let newValue = [...props.value];
if (checked) {
newValue.push(value);
} else {
newValue = newValue.filter((item) => item !== value);
}
emit("update:value", newValue);
};
watch(props.value, (newValue) => {
emit("changeOption", newValue);
});
return {
...toRefs(props),
onChange,
};
},
});
</script>
```
然后在父组件中,你可以监听 `WCheckboxGroup` 组件的 `changeOption` 事件,并在事件处理函数中更新 `checkedList` 的值。修改后的代码如下:
```vue
<template>
<div>
<div>
<div>封装后的多选框</div>
<div>
<w-checkbox-group v-model:value="checkedList" :options="plainOptions" @changeOption="onChangeOption" />
</div>
</div>
</div>
</template>
<script lang="ts">
import WCheckboxGroup from "@/components/w-checkbox-group/checkboxGroup.vue";
import { defineComponent, reactive, toRefs } from "vue";
const plainOptions = [
{ label: "Apple", value: "Apple" },
{ label: "Pear", value: "Pear" },
{ label: "cc", value: "cc" },
];
export default defineComponent({
components: {
WCheckboxGroup,
},
setup() {
const state = reactive({
indeterminate: true,
checkAll: false,
checkedList: ["Apple"],
});
const onChangeOption = (val: any) => {
state.checkedList = val;
};
return {
...toRefs(state),
plainOptions,
onChangeOption,
};
},
});
</script>
```
这样修改后,当子组件中选项的选中状态发生变化时,父组件的 `checkedList` 数据也会更新,并重新渲染视图。
阅读全文