tags: ‘vue’
categories: ‘vue’
vue循环时动态设置ref,获取ref报错
注意:ref不需要唯一
错误使用
设置ref
<li v-for="(item, index) in arr"><p><input :ref="name + index" type="file" @change="uploadImgSave($event, index)" style="display: none;"><button @click="uploadImg(index)">点击上传图片</button></p><img :src="item" alt="" width="150" height="150"></li>
获取ref — 这个是有问题的
获取不到ref元素,调试发现,获取到的是undefined
uploadImg(i){this.$refs[name + i].click(); // 报错}
正确使用
没必要给循环列表的每一个元素加上不一样的ref,而只用给他们都加上一样的ref,根据此ref获取到的是一个数组列表,然后根据index即可定位该元素
设置ref
<input :ref="name" type="file" @change="uploadImgSave($event, index)" style="display: none;">
获取ref
uploadImg(i){this.$refs[name][i].click();}
解决完整例子:
<template><div class="main"><ul><li v-for="(item, index) in arr"><p><input :ref="name" type="file" @change="uploadImgSave($event, index)" style="display: none;"><button @click="uploadImg(index)">点击上传图片</button></p><img :src="item" alt="" width="150" height="150"></li></ul></div></template><script>let _this = '';export default{data(){return{name: 'inputAll',arr: ['', '' ]}},created(){_this = this;},methods:{uploadImg(i){console.log(i, this.$refs[this.name][i]);this.$refs[this.name][i].click();},uploadImgSave(e, i){var reader = new FileReader();reader.onload = (function (file) {return function (e) {_this.$set(_this.arr, i, this.result);}})(e.target.files[0]);reader.readAsDataURL(e.target.files[0]);}},}</script>
