用vue3中的element-plus写一个当编辑表格使当前行变成input框,鼠标离开时,触发弹出框
时间: 2024-03-20 22:39:29 浏览: 20
可以参考以下代码实现:
```vue
<template>
<div>
<el-table :data="tableData">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
<el-table-column label="操作">
<template #default="{ row }">
<el-button @click="editRow(row)">编辑</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog :visible.sync="dialogVisible" v-if="editData">
<el-form ref="form" :model="editData">
<el-form-item label="姓名" prop="name">
<el-input v-model="editData.name"></el-input>
</el-form-item>
<el-form-item label="年龄" prop="age">
<el-input v-model.number="editData.age"></el-input>
</el-form-item>
</el-form>
<div slot="footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="saveEdit">确 定</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import { ref } from 'vue'
import { ElTable, ElTableColumn, ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus'
export default {
components: { ElTable, ElTableColumn, ElButton, ElDialog, ElForm, ElFormItem, ElInput },
setup() {
const tableData = ref([
{ name: '张三', age: 20 },
{ name: '李四', age: 25 },
{ name: '王五', age: 30 }
])
const editData = ref(null)
const dialogVisible = ref(false)
const editRow = (row) => {
editData.value = Object.assign({}, row)
}
const saveEdit = () => {
const index = tableData.value.findIndex(item => item === editData.value)
tableData.value.splice(index, 1, editData.value)
editData.value = null
dialogVisible.value = false
}
return { tableData, editData, dialogVisible, editRow, saveEdit }
}
}
</script>
```
以上代码中,我们使用了 vue3 和 element-plus 提供的组件和 API,来实现编辑表格的功能。具体实现步骤如下:
1. 在 setup 函数中使用 ref 创建响应式变量 tableData、editData 和 dialogVisible,分别用于存储表格数据、编辑数据和编辑对话框的显示状态。
2. 在模板中使用 el-table 组件渲染表格,并使用 el-table-column 组件定义表格列,其中第三列使用了插槽和 el-button 组件来实现编辑按钮。
3. 在表格的编辑按钮点击事件中,调用 editRow 方法,并将当前行的数据保存到 editData 变量中。
4. 在编辑对话框中使用 el-dialog、el-form 和 el-form-item 组件来定义表单项,然后使用 el-input 组件和 v-model 指令来绑定编辑数据。
5. 在编辑对话框的确定按钮点击事件中,调用 saveEdit 方法,更新表格数据并关闭编辑对话框。
6. 在 el-dialog 组件上使用 v-if 指令来判断是否显示编辑对话框,只有在编辑数据存在时才显示对话框。
需要注意的是,我们在 el-input 组件上使用了 v-model.number 指令来将年龄属性绑定为数字类型,这样在保存数据时才能正确计算年龄的值。另外,我们还使用了 Object.assign 方法来复制当前行的数据,避免直接修改原始数据造成不必要的副作用。