vue中怎么触发隐藏input:file的change事件?

现在的场景是这样的 我界面上有个图片 还有个隐藏的input:file 然后我想点击图片触发input:file的change事件 实现选择图片上传 现在的问题就是 隐藏的input:file的change事件触发不了 我在image的点击事件里 就是触发不了 还希望大神指导下
Ps:已使用过的方式

  • input:file 加个ref 通过this.$refs.inputref.change/click ×
  • 给input:file 加个id或者class 然后document.getElementById/document.querySelector('id or class').onchange= function(){} ×
阅读 22.1k
5 个回答

我猜你是想要这么一个东西,如果是的话用css即可解决。
图片描述

实现思路如下:
1.input设置为opacity:0;
2.img的z-index < input的z-index

图中实现的部分代码:
HTML部分

      <img v-if="item.data != ''" v-bind:src=" item.data || index " >
      <input type="file" :id=" item.name " @change="pushImg($event,index)" accept="image/jpeg,image/png,image/gif">

CSS部分

  .imgArea img{
    position: absolute;
    top: 0;
    left: 0;
    width: 50px;
    height: 50px;
  }
  .imgArea input{
    position: absolute;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
    z-index: 5;
  }

this.$refs._testFile.dispatchEvent(new MouseEvent('click')) 完美解决

new一个事件出来,手动触发试试看

按钮触发,使用js获取input 没啥大毛病

<template>
  <div>
    <el-button :loading="loading" type="primary" @click="handleUpload">select excel file</el-button>
    <input id="excel-upload-input" type="file" accept=".xlsx, .xls" class="c-hide" @change="handkeFileChange">
  </div>
</template>
  methods: {
    handleUpload() {
      document.getElementById('excel-upload-input').click()
    },
    handkeFileChange(e) {
             //upload
    }
  }

通过label内包img,将label的for属性设置为input的id即可

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