创建table实例页
views/table.vue
<template>
<h1>table page</h1>
</template>
<script>
import { getTableData } from '@/api/data'
export default {
data () {
return {
tableData: [],
columns: [
{ key: 'name', title: '姓名' },
{ key: 'age', title: '年龄', editable: true },
{ key: 'email', title: '邮箱', editable: true }
]
}
},
mounted () {
getTableData().then(res => {
this.tableData = res
})
}
}
</script>
关联路由
{
path: 'table',
name: 'table',
component: () => import('@/views/table.vue')
}
请求接口
api/data.js
import axios from './index'
export const getTableData = () => {
return axios.request({
url: '/getTableData',
method: 'get'
})
}
模拟数据
main.js
if (process.env.NODE_ENV !== 'production') require('./mock')
mock/index.js
import Mock from 'mockjs'
import { getTableData } from './response/data'
Mock.mock(//getTableData/, 'get', getTableData)
export default Mock
mock/response/data.js
import {
doCustomTimes
} from '@/lib/tools'
import Mock from 'mockjs'
export const getTableData = () => {
const template = {
name: '@name',
'age|18-25': 0,
email: '@email'
}
let arr = []
doCustomTimes(5, () => {
arr.push(Mock.mock(template))
})
}
函数封装
lib/tools.js
// 调用times次callback
export const doCustomTimes = (times, callback) => {
let i = -1
while (++i < times) {
callback()
}
}
_c/edit-table/edit-table.vue
<template>
<Table :columns="insideColumns" :data="value"></Table>
</template>
<script>
import clonedeep from 'clonedeep'
export default {
name: 'EditTable',
data () {
return {
insideColumns: [],
edittingId: '',
edittingContent: ''
}
},
props: {
columns: {
type: Array,
default: () => []
},
value: {
type: Array,
default: () => []
}
},
watch: {
columns () {
this.handleColumns()
}
},
methods: {
handleClick ({ row, index, column }) {
if (this.edittingId === `${column.key}_${index}`) {
let tableData = clonedeep(this.value)
tableData[index][column.key] = this.edittingContent
this.$emit('input', tableData)
this.$emit('on-edit', { row, index, column, newValue: this.edittingContent })
this.edittingId = ''
this.edittingContent = ''
} else {
this.edittingId = `${column.key}_${index}`
}
},
handleInput (newValue) {
this.edittingContent = newValue
},
handleColumns () {
const insideColumns = this.columns.map(item => {
if (!item.render && item.editable) {
item.render = (h, { row, index, column }) => {
const isEditting = this.edittingId === `${column.key}_${index}`
return (
<div>
{isEditting ? <i-input value={row[column.key]} style=" 50px;" on-input={this.handleInput}></i-input> : <span>{row[column.key]}</span>}
<i-button on-click={this.handleClick.bind(this, { row, index, column })}>{ isEditting ? '保存' : '编辑' }</i-button>
</div>
)
}
return item
} else return item
})
this.insideColumns = insideColumns
}
},
mounted () {
this.handleColumns()
}
}
</script>