在vue的项目中做图片上传时,我通过上传图片后获取到input中的files属性将其进行处理,然后将其转换为base64传给后台。

这个方法用在非v-for上动态生成的ref上时,可以通过 this.$refs.name.files[0]获取到相关元素,但是将这个方法用在v-for动态上传的列表中,而且ref也是通过动态生成的时候就获取不到目标元素的files。结论在最后,可以直接看。

我单独上传图片的方法是

    uploadImg(refName) {        let file = this.$refs[refName].files[0];        let that = this;        let reader = new FileReader();        let imgUrlBase64;        if (file) {            imgUrlBase64 = reader.readAsDataURL(file);            let name = file.name.split(".");            reader.onload = function(e) {                let imgFile= reader.result.substring(                    reader.result.indexOf(",") + 1                );                 let obj = {                    img: [                        {                            originalFileName: name[0],                            fileExtension: "." + name[1],                            fileContent: imgFile                        }                    ]                };                that.$axios                    .post("www.baidu.com", {                        obj: JSON.stringify(obj)                    })                    .then(res => {                        let _data = res.data.xxx;                        if (_data.xxx== "1") {                            let imgURL  = _data.img;                            that.imgList.push(imgURL);                        }                    })                    .catch(err => {                        console.log(err);                    });            };        }    }

该方法在不是通过v-for生成的ref时,可以正常使用,但是将这个方法用在v-for动态上传的列表中,而且ref也是通过动态生成的时候就遇到了问题。
template中的代码是:

    <ul>        <li v-for="(item, index) in list" :key="index">            <title>{{item.name}}</title>            <input                    type="file"                    accept="image/png, image/gif, image/jpeg"                    :ref="'img' + index"                     @change="uploadImg('img' + index)"                >        </li>    </ul>

经过一番排查之后,我发现这个问题是ref的问题: 当template中直接使用ref时,它会直接返回ref,但是template中这个ref是在v-for中动态生成时,它返回的是一个数组,必须通过 this.$refs[refName].files[0]才可以获取到对应的元素。所以上面的方法在加一个判断即可实现。