问题遇到的现象和发生背景
vue + element plus 2.0.1 el-table组件,在data中使用filter,并根据是选中talbe中的数据行,更改“删除”按钮的状态。
问题相关代码,请勿粘贴截图
<template>
<div>
<div>
<el-input clearable placeholder="搜索..." prefix-icon="el-icon-search" v-model="serarchText"></el-input>
</div>
<el-table border stripe
:data="roleData.filter((data) => !serarchText || data.name.includes(serarchText))"
:header-cell-style="{background:'#409EFF',color:'#FFF'}"
@selection-change="handleRoleChange">
<!--TODO::data 如果使用roleData.filter,会导致当前table无法选中数据-->
<el-table-column align="center" type="selection" width="50" />
<el-table-column align="center" label="ID" prop="id" width="50" />
<el-table-column align="center" label="角色名称" prop="name" width="150" />
<el-table-column align="center" label="角色代码" prop="code" width="120" />
</el-table>
<div>
<!--<el-button type="danger" :disabled="buttonDisabled">删除角色</el-button>-->
<el-button type="danger" :disabled="roleSelectedData.length === 0">删除角色</el-button>
</div>
</div>
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue';
// const buttonDisabled = ref(false);
const roleData = ref();
roleData.value = [
{
id: 1,
code: 'ROLE_TEST0_1',
name: '测试角色3',
enabled: true
},
{
id: 3,
code: 'ROLE_TEST0_3',
name: '系统开发员',
enabled: true
}
];
const roleSelectedData = ref();
roleSelectedData.value = [];
const serarchText = ref();
//
const handleRoleChange = (value: any) => {
roleSelectedData.value = value;
console.log('handleRoleChange >> roleIds = ', roleSelectedData.value);
};
watch(roleSelectedData, (newValue, oldValue) => {
// if (newValue.length > 0) {
// buttonDisabled.value = true;
// } else {
// buttonDisabled.value = false;
// }
// const _temp = JSON.parse(JSON.stringify(newValue));
// if (_temp.length === 0) {
// buttonDisabled.value = true;
// } else {
// buttonDisabled.value = false;
// }
console.log('Watch(roleSelectedData) newValue = ', newValue, ' oldValue = ', oldValue);
});
</script>
运行结果及报错内容
此时table的行无法选中,删除按钮的disable状态不变更。
通过watch打印roleSelectedData数据的状态,发现此时点击一下某数据行时,控制台会打印两次watch结果,也就是:
handleRoleChange >> roleIds = Proxy {0: Proxy}
Watch(roleSelectedData) newValue = Proxy {0: Proxy} oldValue = Proxy {}
handleRoleChange >> roleIds = Proxy {}
Watch(roleSelectedData) newValue = Proxy {} oldValue = Proxy {0: Proxy}
我的解答思路和尝试过的方法
一头雾水,不知道为啥会这样,还请不吝赐教
我想要达到的结果
点击数据行时,如果此时有选中的行,则删除按钮解除disable状态;如果一行数据都没选中,此时删除按钮disable