LoginSignup
85
75

More than 5 years have passed since last update.

[Vue.js]クリックすると編集可能に切り替わるテキスト

Posted at

はじめに

  • クリックすると編集可能に切り替わる
  • フォーカスを外すとテキストに戻る

わりとよくあるアレをvue.jsで

デモ

説明

js

Vue.directive('auto-focus', {
  bind: function () {
    var el = this.el;
    Vue.nextTick(function(){
        el.focus();
    });
  }
});
  • このカスタムディレクティブは要素がレンダリングされたときに、対象の要素にフォーカスします。
  • bindした瞬間はまだ要素はレンダリングされていないので、Vue.nextTick()で待っています。
html
  <div v-if="!edit" v-text="value" v-on:click="edit = true"></div>
  <input v-if="edit" type="text" 
          v-model="value" v-on:blur="edit = false"  v-auto-focus>
  • レンダリングされたときにフォーカスするので、v-showではなくv-ifで切り替えています。

コード全文

js

Vue.directive('auto-focus', {
  bind: function () {
    var el = this.el;
    Vue.nextTick(function(){
        el.focus();
    });
  }
})

new Vue({
    el: '#app',
    data: function(){
        return {
        value: 'Test',
        edit: false
      }
    }
})
html
<div id="app">
  <div class="text" v-if="!edit" v-text="value" v-on:click="edit = true"></div>
  <input v-if="edit" type="text" 
          v-model="value" v-on:blur="edit = false"  v-auto-focus>
</div>
85
75
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
85
75