vue 封裝元件上傳img
阿新 • • 發佈:2018-11-27
var _uploadTemplate = '<div>'+ '<input type="file" name="file" v-on:change="change" id="file" accept="img.png" style="display: none;">' + '</div>'; Vue.component('vue-upload', { template: _uploadTemplate, props: ["accept","backfun", "height", "width"], data: function() { return { model: { code: 0, message: "", fileUrl: "" } } }, methods: { change: function () { var that= this; var file = document.getElementById("file"); // 檔案流 varfileData=file.files[0]; var fileType=file.value.toLowerCase().split('.');//以“.”分隔上傳檔案字串 //展示資料用 //限制圖片格式 if(fileType[fileType.length-1]!='jpg'&&fileType[fileType.length-1]!='png'&&fileType[fileType.length-1]!='jpeg'){ document.getElementById("file").value = ""; that.model.code =1; that.model.message="圖片格式不正確!"; that.backfun(that.model); return; } if (fileData.size > 5242880) { document.getElementById("file").value = ""; that.model.code = 2; that.model.message="圖片檔案太大!"; that.backfun(that.model); return; } var reader = new FileReader(); reader.readAsDataURL(fileData,"UTF-8"); reader.onload = function (evt) { var fileString = evt.target.result; that.model.code = 0; that.model.fileUrl =fileString; that.backfun(that.model); } } }, }); var _loadingTemplate ='<transition enter-active-class="animated fadeIn" leave-active-class="animated fadeOut"><div style="display: block;" v-if="show"></transition>'; Vue.component('coinbig-loading', { template: _loadingTemplate, props: ["show"], });
html 樣式就不寫了 沒什麼東西
呼叫元件
<div class="middle-image"> <div class="middle-imageson"> <img class="middle-imgas" :src="imgSrcTx||'/url'"/> //上傳後會傳到這。有一個預設的img </div> <div class="middle-imagesona" v-on:click="upload()">修改</div> <vue-upload :ext="'png,jpeg,jpg'":backfun="uploadBack" :width="64" :height="64"></vue-upload> </div>
呼叫js
//頭像上傳圖片 upload:function(){ $("#file").trigger("click"); }, //圖片SHANGCHUAN uploadBack:function(data){ var that = this; if(data.code!=0){ return; } that.imgSrcTx = data.fileUrl; that.SubmitsendImg(); }, SubmitsendImg:function () { var that = this; Comm.runebws("url",{avatar:that.imgSrcTx},"post",function (result) { if(result.code==0){ }else{ that.msgFun(result.msg); return } }) }