我有自定义文本字段,当对话框打开时我必须关注它的功能。我尝试使用 vue.js refs
聚焦它:
代码:
<v-app id="app">
<v-row align="center">
<v-col class="text-center" cols="12">
<v-btn color="primary" @click="openDialog()">Open dialog</v-btn>
</v-col>
</v-row>
<v-dialog v-model="dialog">
<v-card>
<v-card-title
class="headline grey lighten-2"
primary-title
>
Dialog
</v-card-title>
<v-card-text>
<v-row>
<v-col cols="6" class="ml-2">
<v-text-field
ref="name"
placeholder="Enter your name..."
type="text"
solo
flat
outlined
></v-text-field>
<v-btn
color="indigo"
dark
@click = "setFocusName()"
>Set focus</v-btn>
</v-col>
</v-row>
</v-card-text>
</v-card>
</v-dialog>
</v-app>
Javascript:
new Vue({
el: '#app',
vuetify: new Vuetify(),
data () {
return {
dialog: false
}
},
methods: {
setFocusName() {
this.$refs.name.focus();
},
openDialog() {
this.dialog = !this.dialog
this.setFocusName()
}
}
});
当我单击打开对话框按钮时,我的文本字段没有获得焦点。在这里你可以看到我的完整 codepen
打开对话框时如何正确聚焦?
最佳答案
您的代码的问题是您试图在实际呈现之前访问 $ref
,这是一个包含工作代码的沙箱:
https://codepen.io/Djip/pen/ZEYezzm?editors=1011
为了解决该错误,我添加了一个 setTimeout
以在对话框打开 0.2 秒后触发焦点。我首先尝试使用 $nextTick
,但这还不足以完成这项工作 - 您可以尝试调整计时器,使其尽可能低。
setFocusName() {
this.$refs.name.focus();
},
openDialog() {
this.dialog = !this.dialog
setTimeout(() => {
this.setFocusName()
}, 200)
}
关于javascript - 对话框打开时在对话框内设置焦点文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59407003/