You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue实现图片预览报Uncaught TypeError: callback is not a function如何解决

报错原因及修复方案
  • 未定义@input绑定的inputImageRenderer方法

模板中给<b-form-file>绑定了@input="inputImageRenderer"事件,如果组件内没有声明这个方法,事件触发时Vue找不到对应回调就会直接抛出「callback is not a function」错误,这是最高概率的触发原因。不需要该事件可以直接删除模板中的@input绑定,需要的话补充定义对应方法即可。

  • @change事件参数使用错误

BootstrapVue的<b-form-file>组件的change事件回调参数直接是选中的File对象数组,不是原生input事件对象,代码中写e.target.files是错误用法,e本身就是files数组,不需要再取target属性。

  • FileReader的onload回调this指向错误

给reader.onload赋值普通函数时,函数内部的this指向FileReader实例,不是Vue组件实例,无法正确给this.profilePhoto赋值,还可能触发属性未定义相关的后续错误。

修复后代码

模板部分

<b-form-file
      ref="refInputEl"
      v-model="profileFile"
      accept=".jpg, .png, .gif"
      :hidden="true"
      plain
      @change="onFileChange"
      <!-- 不需要input事件直接删除该行,需要的话保留并补充对应方法 -->
/>

JS逻辑部分

onFileChange(files) {
  if (files && files[0]) {
    const reader = new FileReader()
    // 改用箭头函数,this继承外层Vue组件实例
    reader.onload = (event) => {
      console.log(event.target.result)
      this.profilePhoto = event.target.result
    }
    reader.readAsDataURL(files[0])
  }
},
// 保留@input绑定的话需要补充该方法
inputImageRenderer() {
  // 编写对应业务逻辑即可
}

内容的提问来源于stack exchange,提问作者Bryan Sanjuan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 03:45:03