サンプルソース(Vue Component)
<template>
<div>
<template v-if="isEdit">
<el-input @blur="isEdit = false" id="editableText" v-model="editValue" ref="editValue"></el-input>
</template>
<template v-else>
<span @click="handleEdit()">{{ editValue }}</span>
</template>
</div>
</template>
<script lang="ts">
import Vue from "vue"
import { ClientUtil } from "./../utils/clientUtil"
export default Vue.extend({
data() {
return {
editValue: "test",
isEdit: false,
}
},
methods: {
handleEdit(index: number, key: number) {
this.isEdit = true
this.$nextTick(() => {
document.getElementById("editableText")!.focus()
// (this.$refs.exampleEdit as Vue).$el.children[0].focus()
})
},
},
})
</script>
Vue Elementのel-inputにfocusが当たらない場合
Vue的なやり方だと以下
this.$refs.exampleEdit.$el.children[0].focus()
ref="editValue" を指定するとthis.$refs.editValue でアクセスできるようになる。
$el で生のHTMLを取得することができる。
ただし$el.focus()のようにしてもフォーカスは当たらない。
<el-input></el-input> がHTMLに展開されたときに以下のようになるため
<div class="el-input">
<input type="text" autocomplete="off" id="editableText" class="el-input__inner">
</div>
input要素にアクセスするために $el.children[0].focus() のようにする。でわざわざこれをやるかと言うとまあやらないだろう。
nexttickはDOM更新後に走る。DOMを直接更新する場合はほぼ必須というかないとわかりにくいバグが発生する。
参考
https://jp.vuejs.org/v2/guide/components.html
https://qiita.com/akicho8/items/b4d071ea7eae562f529d
https://forum.vuejs.org/t/how-to-set-focus-to-input/10672/8