Vue v-for 新文本区域自动对焦
Vue v-for autofocus on new 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]
returns 一个数组,所以只需访问第一个并在
上调用 .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
是一个对象而不是空字符串
我正在创建一个博客,希望用户在按下回车键时能够创建新的文本区域,并使其自动聚焦于新创建的文本区域。我试过使用 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]
returns 一个数组,所以只需访问第一个并在
.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
是一个对象而不是空字符串