我正在创建一个博客,希望用户在按Enter时能够创建新的textareas,并使它自动聚焦于新创建的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()})
}
最佳答案
您在正确的路径上,但是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
在一个对象中而不是空字符串