slot-scope
從 3.2.0 版本開始支持 slot-scope 寫法。
在 columns 的某列聲明 slot 后,就可以在 Table 的 slot 中使用 slot-scope。
slot-scope 的參數有 3 個:當前行數據 row,當前列數據 column,當前行序號 index。
示例可編輯表格
<template>
<Table :columns="columns" :data="data">
<template slot-scope="{ row, index }" slot="name">
<Input type="text" v-model="editName" v-if="editIndex === index" />
<span v-else>{{ row.name }}</span>
</template>
<template slot-scope="{ row, index }" slot="age">
<Input type="text" v-model="editAge" v-if="editIndex === index" />
<span v-else>{{ row.age }}</span>
</template>
<template slot-scope="{ row, index }" slot="birthday">
<Input type="text" v-model="editBirthday" v-if="editIndex === index" />
<span v-else>{{ getBirthday(row.birthday) }}</span>
</template>
<template slot-scope="{ row, index }" slot="address">
<Input type="text" v-model="editAddress" v-if="editIndex === index" />
<span v-else>{{ row.address }}</span>
</template>
<template slot-scope="{ row, index }" slot="action">
<div v-if="editIndex === index">
<Button @click="handleSave(index)">保存</Button>
<Button @click="editIndex = -1">取消</Button>
</div>
<div v-else>
<Button @click="handleEdit(row, index)">操作</Button>
</div>
</template>
</Table>
</template>
<script>
export default {
data () {
return {
columns: [
{
title: '姓名',
slot: 'name'
},
{
title: '年齡',
slot: 'age'
},
{
title: '出生日期',
slot: 'birthday'
},
{
title: '地址',
slot: 'address'
},
{
title: '操作',
slot: 'action'
}
],
data: [
{
name: '王小明',
age: 18,
birthday: '919526400000',
address: '北京市朝陽區芍葯居'
},
{
name: '張小剛',
age: 25,
birthday: '696096000000',
address: '北京市海淀區西二旗'
},
{
name: '李小紅',
age: 30,
birthday: '563472000000',
address: '北京市通州區永順地區'
},
{
name: '周小偉',
age: 26,
birthday: '687024000000',
address: '深圳市南山區深南大道'
}
],
editIndex: -1, // 當前聚焦的輸入框的行數
editName: '', // 第一列輸入框,當然聚焦的輸入框的輸入內容,與 data 分離避免重構的閃爍
editAge: '', // 第二列輸入框
editBirthday: '', // 第三列輸入框
editAddress: '', // 第四列輸入框
}
},
methods: {
handleEdit (row, index) {
this.editName = row.name;
this.editAge = row.age;
this.editAddress = row.address;
this.editBirthday = row.birthday;
this.editIndex = index;
},
handleSave (index) {
this.data[index].name = this.editName;
this.data[index].age = this.editAge;
this.data[index].birthday = this.editBirthday;
this.data[index].address = this.editAddress;
this.editIndex = -1;
},
getBirthday (birthday) {
const date = new Date(parseInt(birthday));
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month}-${day}`;
}
}
}
</script>