gpt4 book ai didi

javascript - 无法让 Vue 专注于输入

转载 作者:搜寻专家 更新时间:2023-10-30 22:54:29 25 4
gpt4 key购买 nike

我正在尝试使用 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 notre-render immediately. It will update in the next “tick”, when thequeue is flushed. [...]

In order to wait until Vue.js has finished updating the DOM after a datachange, you can use Vue.nextTick(callback) immediately after the datais changed. The callback will be called after the DOM has beenupdated.

(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com