问题描述
开发环境
- vue@3.2.13
- element-plus@2.2.18 (2.2.16版本也会有这个问题)
遇到的问题如下:
点击【马来西亚】,值更新了,但是界面的马来西亚无选中效果。
示例代码
<!-- 子组件 co-select.vue -->
<template>
<el-checkbox-group v-model="checkedList" @change="onChange">
<el-checkbox v-for="co in options" :key="co.key" :label="co">{{ co.name }}</el-checkbox>
</el-checkbox-group>
</template>
<script setup>
import { ref, defineProps } from 'vue';
const props = defineProps({
options: {
type: Array,
default: () => {
return [];
},
},
});
const checkedList = ref([]);
const onChange = (val) => {
console.log('select : ', val);
};
</script>
<!-- 父组件 -->
<template>
<co-select :options="val"></co-select>
</template>
<script setup>
import { ref } from 'vue';
import CoSelect from './co-select.vue';
const val = ref([
{ key: 1, name: '马来西亚' },
{ key: 2, name: '韩国' },
{ key: 3, name: '法国' },
{ key: 4, name: '加拿大' },
{ key: 5, name: '土耳其' },
]);
</script>
问题解析
在 element-plus 新版本中(2.2.16版本以上),多选框的实现更新过,已经不兼容 reactive() 与 ref()对象作为 options 的遍历数组的指定 label 的值,需要使用代理前的原始对象。
解决方案
我们利用 toRaw() 返回代理的原始对象,替换 Checkbox 的 v-for 对象。
我们需要把子组件的代码调整为:
<!-- 子组件 co-select.vue -->
<template>
<el-checkbox-group v-model="checkedList" @change="onChange">
<!-- 替换遍历的对象 -->
<el-checkbox v-for="co in rawOptions" :key="co.key" :label="co">{{ co.name }}</el-checkbox>
</el-checkbox-group>
</template>
<script setup>
import { ref, defineProps, computed, toRaw } from 'vue';
const props = defineProps({
options: {
type: Array,
default: () => {
return [];
},
},
});
const checkedList = ref([]);
// 修改点
const rawOptions = computed(() => {
return toRaw(props.options);
});
const onChange = (val) => {
console.log('select : ', val);
};
</script>
修复后的效果: