Vue3 @input事件函数传参问题咨询:获取元素与ref传递
问题解答
修正后的代码示例
模板部分
<input type="file" id="fieldBoxContentAddPhoto" accept="image/png" @input="inputPhoto($event, fieldBoxContentAddPhoto2, fieldBoxContentAddPhoto3)" > <img alt="" ref="fieldBoxContentAddPhoto2" :src="fieldBoxContentAddPhoto3" style="width:150px;height:150px" >
注意:img的src需使用绑定语法
:src,这样才能响应ref变量的value变化。
脚本部分
const fieldBoxContentAddPhoto2 = ref(); const fieldBoxContentAddPhoto3 = ref(); function inputPhoto(event, imgRef, srcRef){ // 获取触发事件的input元素 const inputElement = event.target; console.log(inputElement); // 正确拿到input元素 console.log(imgRef.value); // img DOM元素 console.log(srcRef.value); // 初始为undefined,可通过.value修改 // 示例:读取选中文件并设置图片src if(inputElement.files.length > 0){ const file = inputElement.files[0]; srcRef.value = URL.createObjectURL(file); } }
问题1:Vue3中@input事件获取触发的input元素
在Vue3的模板事件绑定里,不能用this获取触发元素,需通过$event传递事件对象,再在函数内通过event.target拿到对应的input DOM元素:
- 模板中写
@input="inputPhoto($event, 其他参数)" - 函数内通过
event.target直接获取触发事件的input元素 - 若只需input元素,也可直接传
$event.target,比如@input="inputPhoto($event.target, ...)",此时函数第一个参数就是input元素
问题2:正确传递ref变量并修改其value
直接在模板里传递ref变量本身(如fieldBoxContentAddPhoto3)即可,因为ref是包含.value属性的响应式对象,传递后在函数里可通过变量名.value修改值:
- 模板中直接写
@input="inputPhoto(..., fieldBoxContentAddPhoto3)" - 函数内通过
srcRef.value = 新值修改,绑定了:src的img会自动更新
内容的提问来源于stack exchange,提问作者MGJH
相关产品推荐
相关产品推荐

