vue2+Element--el-table组件中嵌入el-input输入框无法获取焦点、无法编辑问题

741 阅读1分钟

需求描述

在table中嵌入输入框,获得焦点后可编辑。

问题

使用el-table表格组件,在表格中利用插槽嵌入el-input输入框。点击输入框无反应,@input、@focus事件没有触发,导致input框无法获取当前输入框焦点,无法进行输入和编辑。

问题原因

原因不确定,推测原因可能是DOM树渲染时,js执行速度比HTML快,导致输入框对象未获取到,进而focus方法失效。

解决方法

可利用el-tablecell-click事件,在点击输入框时,获取到该输入框对象,手动获取焦点,方法如下所示:

html结构

<el-form ref="fidleForm" :model="form">
  <el-table 
    :data="form.tableData" 
    row-key="index"  
    @cell-click="handleClickCell"
  >
    <el-table-colum prop="name" label="字段名">
        <template slot-scope="scope">
            <el-form-item 
              :prop="'tableData.' + $scope.index + '.name'"
              :rules="{
                required:true,
                tigger:"blur",
                validator:checkName
              }"
            >
              <el-input v-model="scope.row.name" ></el-input>
            </el-form-item>
        </template>
    </el-table-colum>
    <el-table-colum prop="defaultValue" label="默认值">
        <template slot-scope="scope">
            <el-form-item 
              :prop="'tableData.' + $scope.index + '.defaultValue'"
              :rules="{
                required:true,
                tigger:"blur",
                validator:checkName
              }"
            >
              <el-input 
                  v-model.trim="scope.row.defaultValue" 
                  @focus="handleFocusInput(scope.row)"    
              />
            </el-form-item>
        </template>
    </el-table-colum>
  </el-table>
</el-form>

方法

// handleClickCell方法,使用event判断当前节点类型,event具体内容可自行打印查看
handleClickCell(row,column, cell, event){
	if (event.target.nodeName === "INPUT" || event.target.nodeName === "TEXTAREA") {
    	event.target.focus();
    }
},
handleFocusInput(row){
  ...
}

参考文献: