LoginSignup
0
0

More than 3 years have passed since last update.

[vue.js] クリックすると編集可能に切り替え、入力した後、input value を取得する(v-if/v-show $refs)

Last updated at Posted at 2020-11-26

参考先「1」でinput実装したけど、更新されたinput値はどうやって取得するかは苦戦した!

v-ifを使う時に、$refsでinput valueなどを取得したいのに、undefined になっていることがよくあります!($refs.inputまで値出ているけど、$refs.input.XXXにすると、undefinedになった)

色々調べて、原因はわかった、参考先「2」より

ref の登録タイミングに関する重要な注意事項として、参照自体は、render 関数の結果として作成されているため、最初の描画においてそれらにアクセスすることができません。それらはまだ存在しておらず、$refs はリアクティブではなく、従ってデータバインディングのためにテンプレートでそれを使用すべきではありません。

のためです!
下記の方法で一応、編集モードからテキストモードに切り替えると、更新されたinput値を取得できた!

*** IDを付与して、document.getElementById('post_wgt').innerTextでvalueをgetします ***

<template>
 <div id="app">
  <div class="text" id="post_wgt" v-if="!edit" v-text="value" v-on:click="edit = true"></div>
  <b-inform-input v-if="edit" type="text" ref="input"
          v-model="value" v-on:blur="edit = false"  v-focus></div>
  <b-button @click="onSave()" variant="outline-info" >保存</b-button>
</template>
<script>

export default {
  data () {
    return {
      edit: false
    }
  },
  directives: {
    focus: {
      inserted: function (el) {
        el.focus()
      }
    }
  },
  methods: {
    onSave () {
      this.$nextTick(() => {
       console.log(document.getElementById('post_wgt').innerText)
      )}
    }
  }
}

</script>

参考先:
1、[vue]クリックすると編集可能に切り替わるテキスト
2、vue.js(ref)

0
0
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
0
0