Vue Elementで編集可能なテキストコンポーネントを作成する

一見普通のテキストだけどクリックするとテキストフィールドに切り替わるようなやつ





サンプルソース(Vue Component)



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<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的なやり方だと以下
1
this.$refs.exampleEdit.$el.children[0].focus()

ref="editValue"
を指定するとthis.$refs.editValue でアクセスできるようになる。
$el で生のHTMLを取得することができる。
ただし$el.focus()のようにしてもフォーカスは当たらない。
<el-input></el-input> がHTMLに展開されたときに以下のようになるため
1
2
3
<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

2018年5月17日木曜日