1. 程式人生 > 其它 >element-ui中Table可編輯單元格,選中獲取焦點,失去焦點不可編輯

element-ui中Table可編輯單元格,選中獲取焦點,失去焦點不可編輯

<template>
  <el-table
    ref="editabletable"
    v-loading="loading"
    element-loading-text="載入中"
    :data="dataSource"
    current-row-key="id"
    :header-cell-style="{background:'#F5F5F5',color:'#606266'}"
    :border="true"
    @cell-dblclick="handleCellClick"
  >
    <el-table-column
      prop
="cell0" label="單元格0" align="center" > <template slot-scope="scope"> <el-input-number v-if="scope.row.editable === 'cell0'" v-model="scope.row.cell0" v-focus style="width:80%" :controls="false" @blur="handleInputReset(scope.row)" /> <span v-if
="scope.row.editable !== 'cell0'"> {{ scope.row.cell0 }} </span> </template> </el-table-column> <el-table-column prop="cell1" label="攤銷比例" align="center" > <template slot-scope="scope"> <el-input-number v
-if="scope.row.editable === 'cell1'" v-model="scope.row.cell1" v-focus style="width:80%" :controls="false" @blur="handleInputReset(scope.row)" /> <span v-if="scope.row.editable !== 'cell1'"> {{ scope.row.cell1 }} </span> </template> </el-table-column> </el-table> </template> <script lang="ts"> import Vue from 'vue' export default Vue.extend({ data() { return { dataSource: [{ cell1: '單元格1', cell0: '單元格0', editable: '', isEdit: false, }] } }, directives: { // 註冊一個區域性的自定義指令 v-focus focus: { // 指令的定義 inserted: function (el: HTMLElement) { // 聚焦元素 if (el) { el.querySelector('input').focus(); } } } }, methods: { handleCellClick (row: { [key: string]: any }, column: { [key: string]: any }): void { row.editable = column.property; row.isEdit = true; }, handleInputReset (row: { [key: string]: any }): void { row.editable = ''; } } }) </script>