html图片上传和预览(vue)+vue函数传递当前对象参数,vue数据改变dom未变问题

vue函数传递当前对象参数:@change ="uploadFile($event)"    具体可看图片上传部分

单个文件上传预览:

这里使用button按钮嵌套img实现点击上传,点击button激活隐藏的input的click事件

<button id="load" @click="loadImg()" type="button">
    <img alt="" class="big_img" id="big_img" :src="bigimg" >
    <input type="file" id="load_xls" style="display:none"
           accept="image/gif,image/jpeg,image/jpg,image/png" @change ="uploadFile($event)">
</button>

vue的data:

bigimg: 'images/main.jpg',
bfile: null,

vue上传函数:(vue只是入门很多还是用jquery)

loadImg(){
    $("#load_xls").click();
},
uploadFile(e){
    var that = this;
    /*创建文件读取对象*/
    var reader=new FileReader();
    /*文件存储在file表单元素的files属性中,它是一个数组*/
    var file=e.target.files[0];
    if(file) {
        this.bfile = file  //保存数据,上传时提交
        console.log(this.bfile)
        reader.readAsDataURL(file)
        reader.οnlοad= function(e){
            // 这里的this 指向reader
            that.bigimg = e.target.result  //实现预览
        }
    }
},

readAsDataURL:这是例子程序中用到的方法,该方法将文件读取为一段以 data: 开头的字符串,这段字符串的实质就是 Data URL,Data URL是一种将小文件直接嵌入文档的方案。这里的小文件通常是指图像与 html 等格式的文件。

由于JavaScript的限制,Vue不能检测以下变动的数组:

1.当你通过索引直接设置一个数组项时

2.当你修改数组长度时 例如:vm.items.length = newLength

解决办法:创建一个临时数组转存,当然官方文档时推荐通过vm.$set来修改的,具体自行了解

猜你喜欢

转载自blog.csdn.net/qq_36603180/article/details/105625291