我正在尝试使用 this.$refs.cInput.focus()
(cInput
是一个 ref)但它不起作用。我将能够点击 g
并且输入应该弹出并且光标应该聚焦在其中,准备好输入一些数据。它正在显示,但焦点部分不起作用。我在控制台中没有收到任何错误。
Vue.component('coordform', {
template: `<form id="popup-box" @submit.prevent="process" v-show="visible"><input type="text" ref="cInput" v-model="coords" placeholder =""></input></form>`,
data() {
{
return { coords: '', visible: false }
}
},
created() {
window.addEventListener('keydown', this.toggle)
},
mounted() {
},
updated() {
},
destroyed() {
window.removeEventListener('keydown', this.toggle)
},
methods: {
toggle(e) {
if (e.key == 'g') {
this.visible = !this.visible;
this.$refs.cInput.focus() //<--------not working
}
},
process() {
...
}
}
});
最佳答案
您可以使用 nextTick()
回调:
When you set
vm.someData = 'new value'
, the component will not re-render immediately. It will update in the next “tick”, when the queue is flushed. [...]
In order to wait until Vue.js has finished updating the DOM after a data change, you can use
Vue.nextTick(callback)
immediately after the data is changed. The callback will be called after the DOM has been updated.(source)
在您的切换功能中使用它,例如:
methods: {
toggle(e) {
if (e.key == 'g') {
this.visible = !this.visible;
this.$nextTick(() => this.$refs.cInput.focus())
}
}
}
关于javascript - 无法让 Vue 专注于输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56093602/