VUE项目中无法触发隐藏input[type=file]的事件

VUE的一个页面组件在activeted的时候调用一个函数,创建一个input[type=file]标签,然后点击。
函数代码如下:

quickPhoto() {
        // 创建input
      let file = document.createElement('input')
      file.setAttribute('type', 'file')
      file.setAttribute('capture', 'camera')
      file.setAttribute('accept', 'image/*')
      file.style.display = 'none'
      document.querySelector('body').appendChild(file)
      file.addEventListener('change', ()=>{
        this.$vux.loading.show()
        //压缩图片
        this.$utils.$imgCompress(file.files[0]).then(img=>{
          this.$vux.loading.hide()
          this.params.problemImgs.push(img)
          file.value=""
          delete file.parentNode.removeChild(file)
        }).catch(e=>{
          this.$vux.loading.hide()
          alert(e)
        })
      })
      file.addEventListener('click', ()=>{
        console.log('click')
      })
      file.click()
      window.quickPhoto = window.quickPhoto || this.quickPhoto
    }

页面打开后可以在console看到click,但是没有弹出选择图片的窗口。
但是在控制台手动调用quickPhoto()就可以弹出窗口选择图片,
求解。

阅读 3.6k
2 个回答

浏览器不允许js脚本自动打开文件选择, 必须是用户操作才可以

我遇到过类似问题..找了很久原因,,其实是js的垃圾回收机制问题

你只要把 let file = document.createElement('input')
改为 this.file = document.createElement('input')
就不会有问题了
,
然后这句话不是必须的..可以去掉
document.querySelector('body').appendChild(file)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题