vue-使用vfor动态生成的ref不能通过thisrefsname获取到内容

21次阅读

共计 1203 个字符,预计需要花费 4 分钟才能阅读完成。

在 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] 才可以获取到对应的元素。所以上面的方法在加一个判断即可实现。

正文完
 0