话不多说直接看代码
HTML
<button @click.prevent="upload">上传</button>
<-- 这里的ref必须与setup中return出来的 fileInput 同名 -->
<input type="file" ref="fileInput">
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
setup() {
// 获取 input框的dom节点
const fileInput = ref<null | HTMLInputElement>(null)
const upload= () => {
if(fileInput.value) {
console.log(fileInput.value,'-----')
fileInput.value.click()
}
}
return {
triggerUpload,
fileInput
}
}
})
</script>
其实获取节点和vue2差不多,只不过是写法发生了一些改变
对vue3语法不是很熟悉的老铁可以去看一下vue3的官方文档