javascript - 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()})
}
解决方案
你在正确的道路上,但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
在一个对象而不是一个空字符串中
推荐阅读
- angular - 数据表在角度 html 视图中无法正常工作
- c - 我是否成功释放了动态分配的内存?
- r - 如何使用 stan_glm 从以前的研究中定义信息先验?
- debugging - 如何在 SAP 中调试 DMEE 退出事件
- java - 实现接口的类不能使用自己在 Equals 中插入 Object
- symfony - ApiPlatform - 订单过滤器中的重复 id 字段
- python - 如何在 Python 中以交错方式执行线程
- node.js - 使用 eTag 获取天蓝色块 blob
- r - 根据R中的字符对数据框进行排序
- c# - Microsoft.Graph - 如何从具有不同用户名的共享邮箱发送?