使用Modernize Vuetify VueJS Admin模板时DataTable取消选中不更新数组
Vuetify DataTable取消选中行时数组不更新的问题
我在用Modernize Vuetify VueJS Admin模板的可选择DataTable,选中行时能把项加入数组,但取消选中时数组不会移除对应项。
HTML代码
<v-row> <v-col cols="12" lg="7"> <UiParentCard title="Select Services"> <v-text-field v-model="search" append-inner-icon="mdi-magnify" label="Search" single-line hide-details class="mb-5" /> <v-data-table item-value="name" return-object items-per-page="5" :headers="headers" :items="BasicServices" v-model="selected" :search="search" show-select class="border rounded-md"> </v-data-table> </UiParentCard> </v-col> </v-row> <v-row> <v-col cols="12" lg="7"> <pre>{{ selected }}</pre> </v-col> </v-row>
JS代码
const selected = ref(); const search = ref(); const customsearch = ref(); const headers : any = ref([ { title: 'Name', align: 'start', key: 'name' }, { title: 'Cost', align: 'start', key: 'cost' }, { title: 'Hours', align: 'start', key: 'hours' }, ]) const filtrable = ref('') function filterOnlyCapsText(value: { toString: () => string; } | null, query: string | null, item: any) { return value != null && query != null && typeof value === 'string' && value.toString().toLocaleUpperCase().indexOf(query) !== -1 }
修复方案
1. 初始化selected为空数组
当前selected仅用ref()声明,没有初始化为数组,Vuetify的DataTable需要绑定数组来维护选中状态。修改JS里的声明:
const selected = ref([]);
2. 确保item-value使用唯一标识
你现在用item-value="name",如果存在名称重复的服务,会导致选中/取消逻辑混乱。建议改用每个项的唯一ID(比如数据里的id字段),如果数据没有ID,必须保证name是全局唯一的。若有唯一ID,修改HTML:
<v-data-table item-value="id" ...></v-data-table>
3. 优化搜索过滤逻辑(可选)
原过滤函数里的query没转大写,会导致搜索大小写敏感,可优化:
function filterOnlyCapsText(value: { toString: () => string; } | null, query: string | null, item: any) { return value != null && query != null && typeof value === 'string' && value.toString().toLocaleUpperCase().indexOf(query.toLocaleUpperCase()) !== -1 }
修改后的完整JS代码
const selected = ref([]); const search = ref(''); const customsearch = ref(''); const headers = ref([ { title: '名称', align: 'start', key: 'name' }, { title: '费用', align: 'start', key: 'cost' }, { title: '时长', align: 'start', key: 'hours' }, ]) const filtrable = ref('') function filterOnlyCapsText(value: { toString: () => string; } | null, query: string | null, item: any) { return value != null && query != null && typeof value === 'string' && value.toString().toLocaleUpperCase().indexOf(query.toLocaleUpperCase()) !== -1 }
修改完成后,取消选中行时selected数组会自动移除对应项,可通过页面的<pre>标签实时验证。
内容的提问来源于stack exchange,提问作者Md. Zobair Khondaker Rion
相关产品推荐
相关产品推荐

