HTML
<span :style="{ display : displayTitle }" @dblclick="showInput()">
{{ node.title }}
</span>
<input :style="{ display : displayTitleInput }" type="text"
@blur="hideInput1" @keydown="hideInput2"
@input="changeTitle(node.id , $event.target.value)"
:value="node.title">
JS
data() {
return {
displayTitle: "inline-block",
displayTitleInput: "none"
};
},
showInput() {
this.displayTitle = "none"
this.displayTitleInput = "inline-block"
},
hideInput1() {
this.displayTitle = "inline-block"
this.displayTitleInput = "none"
},
hideInput2(event) {
if (event.keyCode === 13) {
this.hideInput1()
}
},
我是一名初级日语网络开发人员。我英语不好,抱歉。
HTML 在“v-for”(v-for="node in list"
)中。
双击文本时,变成<input>
.
我希望能够在输入出现时将注意力集中在输入上。
我试过了,但没用。
HTML
<span :style="{ display : displayTitle }" @dblclick="showInput(node.id)">
{{ node.title }}
</span>
<input :ref='"input_" + node.id' :style="{display:displayTitleInput}" type="text"
@blur="hideInput1" @keydown="hideInput2"
@input="changeTitle(node.id , $event.target.value)"
:value="node.title">
JS
showInput(id) {
this.displayTitle = "none"
this.displayTitleInput = "inline-block"
this.$nextTick(this.$refs["input_" + id][0].focus())
},
控制台没有错误,但没有工作。
最佳答案
您的主要问题是 $nextTick
接受回调函数,但您正在执行
this.$refs["input_" + id][0].focus()
立即。你可以让你的代码正常工作
this.$nextTick(() => {
this.$refs["input_" + id][0].focus()
})
但是,我认为您会遇到更多问题,您的代码可以变得更简单。
您会发现一个问题是,由于您的样式规则,当您双击其中任何一个节点时,您的所有节点输入都会变得可见。
您可以将 “编辑” 标志存储在 节点
或单独对象中的某处。
下面是一个通过...简化代码的示例
- 利用
ref
的类数组性质在v-for
循环中使用时,和 - 在
@keydown
事件绑定(bind)上使用enter
修饰符
new Vue({
el: '#app',
data: {
list: [
{id: 1, title: 'Node #1'},
{id: 2, title: 'Node #2'}
],
editing: {}
},
methods: {
showInput(id, index) {
this.$set(this.editing, id, true)
this.$nextTick(() => {
this.$refs.input[index].focus()
})
},
hideInput(id) {
this.editing[id] = false
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<ul id="app">
<li v-for="(node, index) in list">
<span v-show="!editing[node.id]" @dblclick="showInput(node.id, index)">
{{ node.title }}
</span>
<input v-show="editing[node.id]" type="text"
ref="input" :value="node.title"
@blur="hideInput(node.id)" @keydown.enter="hideInput(node.id)">
</li>
</ul>
关于javascript - vue.js 将焦点放在输入上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52088691/