try 以下代码段(this
是脚本设置中的其他内容,您不能使用$refs
):
<script setup>
import { ref } from 'vue'
const inputField = ref()
const focusInput = () => {
inputField.value.focus();
};
</script>
const { ref } = Vue
const app = Vue.createApp({
setup() {
const inputField = ref()
const focusInput = () => {
inputField.value.focus()
}
return { focusInput, inputField }
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<button @click="focusInput">Click me to focus on the input</button>
<input ref="inputField" type="text">
</div>