<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue 2 Table with Dropdowns</title> <!-- 引入 Vue 2 --> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> </head> <body> <div id="app"> <table> <thead> <tr> <th v-for="(col, index) in columns" :key="index"> <select v-model="headers[index]"> <option v-for="(item, key) in options" :key="key" :value="item">{{ item }}</option> </select> </th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="(row, rowIndex) in rows" :key="rowIndex"> <td v-for="(col, colIndex) in columns" :key="colIndex"> <select v-model="row[colIndex]"> <option v-for="option in getAvailableOptions(rowIndex, colIndex)" :key="option" :value="option">{{ option }}</option> </select> </td> <td> <button @click="deleteRow(rowIndex)">删除</button> </td> </tr> </tbody> <tfoot> <tr> <td colspan="5"> <button @click="addRow">新建一行</button> </td> </tr> </tfoot> </table> </div> <script> new Vue({ el: '#app', data: { columns: ['列1', '列2', '列3', '列4'], headers: new Array(4).fill(''), rows: [], arr: [ { 0: '会员1' }, { 1: '会员2' }, { 2: '会员3' }, { 3: '会员4' }, { 4: '会员5' } ] }, computed: { options() { return this.arr.map(item => Object.values(item)[0]); } }, methods: { addRow() { const newRow = []; for (let i = 0; i < this.columns.length; i++) { const availableOptions = this.getAvailableOptions(this.rows.length, i); newRow.push(availableOptions.length > 0 ? availableOptions[0] : ''); } this.rows.push(newRow); }, deleteRow(index) { this.rows.splice(index, 1); }, getAvailableOptions(rowIndex, colIndex) { const selectedValues = []; // 收集表头选中的值 if (this.headers[colIndex]) { selectedValues.push(this.headers[colIndex]); } // 收集其他行该列选中的值 this.rows.forEach((row, i) => { if (i!== rowIndex && row[colIndex]) { selectedValues.push(row[colIndex]); } }); return this.options.filter(option =>!selectedValues.includes(option)); } } }); </script> </body> </html>
代码说明:
HTML 部分:
- 创建了一个表格,表头包含四个下拉框,用于设置初始值。
- 表格主体部分使用
v-for
指令循环渲染每一行,每一行包含四个下拉框和一个删除按钮。- 表格底部有一个新建行按钮。
Vue 实例部分:
data
中定义了表格的列名、表头选中值、表格行数据和下拉框选项数组。computed
计算属性options
用于将arr
数组转换为下拉框选项数组。methods
中定义了三个方法:
addRow
:用于新建一行,会调用getAvailableOptions
方法获取可用选项,并将第一个可用选项作为新行的初始值。deleteRow
:用于删除指定行。getAvailableOptions
:用于获取指定行和列的可用选项,会排除表头和其他行已选中的值。通过以上代码,你可以实现一个包含四列表头下拉框和第五列新建行按钮的表格,并且新行的下拉框选项会去除之前已选中的值。