以前は、テーブルの内容を編集するには、編集ボタンをクリックして編集ページに入るか、ポップアップ ウィンドウに移動して行全体を編集する必要がありました。
しかし今回のプロジェクトでは、テーブル内をダブルクリックして該当セルを編集する機能を実装する必要があるため、これまでやったことのない私にとっては新たな挑戦でもあります。
達成する必要がある効果:
オプション 1
プロジェクトでは element-ui を使用しているため、最初に考えたのは、テーブル コンポーネントに移動して、この要件を満たす属性があるかどうかを確認することでした。存在するとは思いませんでした (cell-dblclick)。
実装の効果を見てみましょう (コードの一部)。
<template>
<divclass="Table main">
<el-table
:data="tableData"
@cell-dblclick="tableEdit"
>
<el-table-columnprop="name"label="姓名"width="150"></el-table-column>
<el-table-columnprop="amount1"label="数值1"show-overflow-tooltip>
<template#default="props">
<span>{
{props.row.amount1}}</span>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
tableData: [
{
name: '王小虎',
amount1: '234',
amount2: '3.2',
amount3: 10,
}
],
// 双击表格修改数据
tableEdit(row, column, cell, event) {
if (column.label==='数值1'||column.label==='数值2'||column.label==='数值3') {
constbeforeVal=event.target.textContent;
event.target.innerHTML='';
conststr=`<div class='cell'>
<div class='el-input'>
<input type='text' placeholder='请输入内容'>
</div>
</div>`;
cell.innerHTML=str;
// 获取双击后生成的input 而且根据层级嵌套还会有所变化
constcellInput=cell.children[0].children[0].children[0];
cellInput.value=beforeVal;
cellInput.focus(); // input自动聚焦
// 失去焦点后 将input移除
cellInput.onblur=function () {
constonblurCont=`<div class='cell'>${cellInput.value}</div>`;
cell.innerHTML=onblurCont; // 换成原有的显示内容
};
}
},
</script>
それでおしまい!しかし、本当にそれは可能でしょうか?
よく見てみると、この書き方はまだ限界があり、柔軟性が足りないと感じたので、使用を断念します。
オプション II
アイデア: el-table の cell-dblclick 属性を使用する代わりに、ダブルクリック イベントを監視する変数を設定して、セルに表示されるコンテンツを制御します。
(部分コード):
<el-table :data="tableData.data">
<el-table-columnv-for="prop in tabHeader"
:label="struct.fieldName"
:prop="prop"
align="center"
>
<template#default="scope">
<divv-if="isEdit && scope.row.index === rowInd && scope.column.index === colInd">
<el-tooltip
:content="desc">
<el-inputv-if="struct.inputType === 'Input'&&
struct.type==='Number'"
v-model.number="scope.row[prop]"
@blur="isEdit = false"
@change="inputChange"
></el-input>
<el-inputv-if="struct.inputType === 'Input'&&
struct.type==='String'"
v-model="scope.row[prop]"
@blur="isEdit = false"
@change="inputChange"
></el-input>
</el-tooltip>
<el-select
v-if="struct.inputType === 'Select'"
v-model="scope.row[prop]"
@change="isEdit = false; inputChange()"
>
<el-optionv-for="opt in options"
:label="opt" :value="opt" :key="opt"
></el-option>
</el-select>
</div>
<divv-else@dblclick="dbCell(scope)"class="xiaoShou">
{
{scope.row[prop]}}
</div>
</template>
</el-table-column>
</el-table>
// 双击 出现输入框
constdbCell= (a: any) => {
isEdit.value=true;
rowInd.value=a.row.index;
colInd.value=a.column.index;
};
この実装方法は、よりシンプルで拡張性が高く、執筆習慣に準拠しています。
注意が必要なのは、どのセルがクリックされたかを区別することであり、ドロップダウン ボックスではぼかしを使用できません。