单击“编辑”按钮时,将出现输入字段并自动聚焦。
<button v-if="!editingMode" @click="editingMode = !editingMode">edit</button>
<input v-else type="text" value ref="input">
Run Code Online (Sandbox Code Playgroud)
export default {
name: "App",
components: {
HelloWorld
},
data: function() {
return {
editingMode: false
};
},
methods: {
onClickButton() {
this.editingMode = true;
this.$refs.input.focus();
}
}
};
Run Code Online (Sandbox Code Playgroud)
因为Vue中的重新渲染是同步的,所以当我们调用 时this.$refs.input.focus(),输入字段可能还没有渲染。我经历过两个案例:
Error in v-on handler: "TypeError: Cannot read property 'focus' of undefined"就会出现。小智 5
尝试在this.$nextTick中调用它:
methods: {
onClickButton() {
this.editingMode = true;
this.$nextTick(() => {
this.$refs.input.focus();
})
}
}
Run Code Online (Sandbox Code Playgroud)
https://codesandbox.io/s/sleepy-dew-5mcju
| 归档时间: |
|
| 查看次数: |
1759 次 |
| 最近记录: |