首页 > 解决方案 > Vue v-for 在新文本区域上自动对焦

问题描述

我正在制作一个博客,并希望用户能够在按 Enter 键时创建新的 textarea,并让它自动聚焦在新创建的 textarea 上。我试过使用 autofocus 属性,但这不起作用。我也尝试过使用 nextTick 函数,但这不起作用。我该怎么做呢?

<div v-for="(value, index) in content">
    <textarea v-model="content[index].value" v-bind:ref="'content-'+index" v-on:keyup.enter="add_content(index)" placeholder="Content" autofocus></textarea>
</div>

add_content()定义如下:

add_content(index) {
    var next = index + 1;
    this.content.splice(next, 0, '');
    //this.$nextTick(() => {this.$refs['content-'+next].contentTextArea.focus()})
}

标签: javascriptjqueryvuejs2v-for

解决方案


你在正确的道路上,但this.$refs['content-'+next]返回一个数组,所以只需访问第一个并调用.focus()

add_content(index) {
  var next = index + 1;
  this.content.splice(next, 0, {
    value: "Next"
  });
  this.$nextTick(() => {
    this.$refs["content-" + next][0].focus();
  });
}

工作示例

var app = new Vue({
  el: '#app',
  data() {
    return {
      content: [{
        value: "hello"
      }]
    };
  },
  methods: {
    add_content(index) {
      var next = index + 1;
      this.content.splice(next, 0, {
        value: "Next"
      });
      this.$nextTick(() => {
        this.$refs["content-" + next][0].focus();
      });
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="(value, index) in content">
    <textarea v-model="content[index].value" v-bind:ref="'content-' + index" v-on:keyup.enter="add_content(index);" placeholder="Content" autofocus></textarea>
  </div>
</div>

此外,您在数组中的值似乎是一个对象而不是一个字符串,所以splice在一个对象而不是一个空字符串中


推荐阅读