- <el-table ref="multipleTable" :data="tableData" @selection-change="handleSelectionChange">
- <el-table-column type="selection" width="55" :reserve-selection="true" show-overflow-tooltip>
- </el-table-column>
- <el-table-column prop="name" label="Name"></el-table-column>
- <el-table-column prop="age" label="Age"></el-table-column>
- <el-button @click="toggleSelection">Toggle Selection</el-button>
- </el-table>
复制代码- <script>
- export default {
- data() {
- return {
- tableData: [
- { id: 1, name: 'John', age: 30 },
- { id: 2, name: 'Doe', age: 25 },
- { id: 3, name: 'Smith', age: 35 }
- ]
- };
- },
- methods: {
- toggleSelection() {
- const rowToToggle = this.tableData[0]; // 假设切换第一行的选中状态
- const selected = !rowToToggle.selected; // 切换选中状态
- this.$refs.multipleTable.toggleRowSelection(rowToToggle, selected);
- }
- }
- };
- </script>
复制代码 如果想要在初始化的时候就默认勾选,必要用到this.$nextTick,可以确保在 DOM 更新后执行,以便正确设置初始的选中状态。否则直接用的话报错Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'toggleRowSelection')"
- mounted() {
- // 模拟初始化时默认勾选第一行和第二行
- this.$nextTick(() => {
- this.$refs.multipleTable.toggleRowSelection(this.tableData[0], true);
- this.$refs.multipleTable.toggleRowSelection(this.tableData[1], true);
- });
- }
复制代码 监听了selection-change变乱,想要在手动勾选的时候执行某些操作
- handleSelectionChange(vals) {
- console.log(vals)
- }
复制代码 会发现,初始化的时候由于执行了this.$refs.multipleTable.toggleRowSelection方法,导致selection-change也会主动触发。现实中要想把这两者分开来,可以加一个标识字init来区分。
- <script>
- export default {
- data() {
- return {
- tableData: [
- { id: 1, name: 'John', age: 30 },
- { id: 2, name: 'Doe', age: 25 },
- { id: 3, name: 'Smith', age: 35 }
- ],
- init: true
- };
- },
- mounted() {
- this.tableData = this.tableData.map((v, vIndex) => {
- ...
- that.$nextTick(() => {
- that.$refs.multipleTable.toggleRowSelection(v, true);
- if (...) { // 初始化执行完时的判断条件
- setTimeout(() => {
- that.init = false
- }, 0)
- }
- })
- },
- methods: {
- handleSelectionChange(vals) {
- console.log(vals)
- if(this.init) {
- console.log('初始化时触发的')
- } else {
- console.log('手动勾选时触发的')
- }
- }
- }
- </script>
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |