首页 > 解决方案 > VUE:通过 v-if 显示后选择输入

问题描述

我有以下标记:

<div id="app">
  <button class="button is-primary" @click="showMyTF" ref="mybtn">
    Show my Textfield: 
  </button>
  <input class="input" type="text" value="My textfield value" 
  class="formfield" v-if="showTextField" ref="mytf"/>
</div>

和 Vue 代码:

new Vue({
  el: "#app",
  data: {
    showTextField: false
  },
  methods: {
    showMyTF() {
        this.showTextField = true;

      this.$refs.mybtn.innerText = "There you have it";
      this.$refs.mytf.select();
    }
  }
})

我在这里做了一个 JSFiddle 示例: https ://jsfiddle.net/Pintiboy/Lkec1n5g/

我的问题是:是否可以在显示后立即选择文本字段的文本(通过单击按钮)。它在那里后确实有效(第二次单击按钮),但我希望它在出现后立即被选中。有任何想法吗?

标签: vuejs2

解决方案


您可以使用this.$nextTick

showMyTF() {
  this.showTextField = true;

  this.$refs.mybtn.innerText = "There you have it";

  this.$nextTick(() => {
    this.$refs.mytf.select();
  })

}

jsfiddle中的演示


推荐阅读