使用场景:使用iview的Table,在表格中使用插槽,点击某一个单元格后,被点击的单元格变成可编辑的输入框,失去焦点后又切换回原来的状态。
找一个vue页面直接复制粘贴代码:
<template>
<div style="padding:30px;">
<Table border :columns="columns" :data="data" @on-cell-click="cellHandle">
<template #name="{ row,column,index }">
<Input ref="tableInput" v-model="row.name" v-if="isEdit === column.slot + '-' + row._index" @on-blur="isEdit = '' " />
<span v-else>{{ row.name }}</span>
</template>
<template #age="{ row,column,index }">
<Input ref="tableInput" v-model="row.age" v-if="isEdit === column.slot + '-' + row._index" @on-blur="isEdit = '' " />
<span v-else>{{ row.age }}</span>
</template>
<template #address="{ row,column,index }">
<Input ref="tableInput" v-model="row.address" v-if="isEdit === column.slot + '-' + row._index" @on-blur="isEdit = '' " />
<span v-else>{{ row.address }}</span>
</template>
<template #city="{ row,column,index }">
<Input ref="tableInput" v-model="row.city" v-if="isEdit === column.slot + '-' + row._index" @on-blur="isEdit = '' " />
<span v-else>{{ row.city }}</span>
</template>
<template #job="{ row,column,index }">
<Input ref="tableInput" v-model="row.job" v-if="isEdit === column.slot + '-' + row._index" @on-blur="isEdit = '' " />
<span v-else>{{ row.job }}</span>
</template>
<template #hobby="{ row,column,index }">
<Input ref="tableInput" v-model="row.hobby" v-if="isEdit === column.slot + '-' + row._index" @on-blur="isEdit = '' " />
<span v-else>{{ row.hobby }}</span>
</template>
<template #wife="{ row,column,index }">
<span>{{ row.wife }}</span>
</template>
</Table>
</div>
</template>
<script>
export default {
data () {
return {
columns: [
{title: 'name',key: 'name', slot: 'name'},
{title: 'age', key: 'age',slot:"age"},
{title: 'address', key: 'address',slot:"address"},
{title: 'city', key: "city",slot: "city"},
{title: 'job', key: 'job',slot: "job"},
{title: 'hobby', key: 'hobby',slot: "hobby"},
{title: 'wife', key: 'wife',slot: "wife"},
],
data: [
{
name: 'John Brown',
age: 18,
address: 'New York No. 1 Lake Park',
city:"上海",
job:"工程师",
hobby:"听音乐",
wife:"小李",
},
{
name: 'Jim Green',
age: 24,
address: 'London No. 1 Lake Park',
city:"南京",
job:"机械",
hobby:"看电影",
wife:"小周",
},
{
name: 'Joe Black',
age: 30,
address: 'Sydney No. 1 Lake Park',
city:"杭州",
job:"护士",
hobby:"看书",
wife:"小项",
},
{
name: 'Jon Snow',
age: 26,
address: 'Ottawa No. 2 Lake Park',
city:"合肥",
job:"医生",
hobby:"游玩",
wife:"小方",
}
],
isEdit:"",
}
},
methods: {
cellHandle(row, column) {
// let arr = [0,1,2,3]; // 可以使用列名的.length
// if(arr.indexOf(row._index) >= 0) return // 当点击的是0,1,2,3行的时候,不给this.isEdit赋值,即无法完成切换效果
// if(arr.indexOf(column._index) >= 0) return // 当点击的是0,1,2,3列的时候,不给this.isEdit赋值,即无法完成切换效果
this.isEdit = column.slot + "-" + row._index;
this.$nextTick(()=>{
this.$refs.tableInput && this.$refs.tableInput.focus();
})
},
}
}
</script>
这里通过判断点击的那个单元格的名字和index位置来判断是点击了哪个单元格来实现