Vue3 Element Plus 表格反选功能实现教程
<p>在 Vue3 和 Element Plus 中,要设置表格的反选功能,你可以使用以下步骤:</p>
<ol>
<li>首先,安装 Element Plus 库。你可以通过 npm 或 yarn 安装 Element Plus。</li>
<pre><code>bash
npm install element-plus
</code></pre>
<li>在你的 Vue 组件中引入 Element Plus 的 Table 和 Table Column 组件。</li>
<pre><code>vue
<template>
<el-table
:data='tableData'
style='width: 100%'
@selection-change='handleSelectionChange'
v-model:selected-items='selectedItems'
:row-key='row => row.id'
:select-on-indeterminate='false'
:default-sort='{ prop: 'id', order: 'descending' }'
:row-class-name='rowClassName'
>
<el-table-column type='selection' width='55'></el-table-column>
<el-table-column prop='id' label='ID' sortable></el-table-column>
<el-table-column prop='name' label='Name' sortable></el-table-column>
<el-table-column prop='age' label='Age' sortable></el-table-column>
<el-table-column prop='gender' label='Gender' sortable></el-table-column>
</el-table>
</template>
<script>
import { ref } from 'vue';
import { ElTable, ElTableColumn } from 'element-plus';
export default {
components: {
ElTable,
ElTableColumn,
},
setup() {
const tableData = ref([
{ id: 1, name: 'John', age: 25, gender: 'Male' },
{ id: 2, name: 'Jane', age: 30, gender: 'Female' },
{ id: 3, name: 'Bob', age: 35, gender: 'Male' },
]);
const selectedItems = ref([]);
const handleSelectionChange = (selectedRows) => {
selectedItems.value = selectedRows;
};
const rowClassName = (row) => {
if (selectedItems.value.includes(row)) {
return 'row-selected';
}
};
return {
tableData,
selectedItems,
handleSelectionChange,
rowClassName,
};
},
};
</script>
<style>
.row-selected {
background-color: #e6f7ff;
}
</style>
<p></code></pre></p>
<p>在上面的代码中,我们使用<code>el-table</code>组件来渲染表格,使用<code>el-table-column</code>组件定义表格的列。其中,通过设置<code>type='selection'</code>来显示选择框列。</p>
<p>我们使用<code>@selection-change</code>事件监听选择框的变化,并将选择的行赋值给<code>selectedItems</code>变量。</p>
<p>在<code>row-class-name</code>属性中,我们定义了一个函数<code>rowClassName</code>来设置选中行的样式。如果行在<code>selectedItems</code>数组中,我们将其样式设置为<code>row-selected</code>。</p>
<p>最后,在<code><style></code>标签中,我们定义了<code>row-selected</code>样式,用于设置选中行的背景颜色。</p>
<p>这样,你就可以在 Vue3 和 Element Plus 中实现表格的反选功能了。</p>
原文地址: https://www.cveoy.top/t/topic/qjwr 著作权归作者所有。请勿转载和采集!