上傳圖片元件的封裝
阿新 • • 發佈:2021-01-23
技術標籤:vue
1.圖片上傳元件
<template>
<div style="display: inline-block;margin-bottom: 24px;position: relative">
<input
style="opacity: 0;width: 0;height: 0;position: absolute;"
type="file"
accept="image/png, image/jpg, image/jpeg"
: id="fileInputId"
/>
<Button
:loading="loading.upload"
v-if="!readPath"
style="height: 150px;width: 150px;padding: 0;"
type="dashed"
@click="showSelect"
>
<div>
<Icon type= "md-add" />
</div>
<div>上傳</div>
</Button>
<Button
v-if="readPath"
style="padding: 0;height: 150px;width: 150px;"
type="dashed"
@click="showImg"
>
<img height="145" width="145" :src="readPath" alt />
</Button>
<Modal v-model="modal" width="800">
<div slot="header">
<div style="height: 48px;">
<Button :loading="loading.upload" @click="showSelect" type="primary">重新上傳</Button>
</div>
</div>
<div style="width: 800px;margin: -16px;">
<img width="800" alt :src="readPath" />
</div>
<div slot="footer"></div>
</Modal>
<div class="subtitle">{{ subtitle }}</div>
</div>
</template>
<script>
export default {
name: "uploadImg",
props: {
fileInputId: {
type: String,
required: true
},
url: {
type: String,
required: false,
default: ""
},
subtitle: {
type: String,
required: false,
default: "支援格式:PNG、JPG、JPEG,建議圖片尺寸64*64"
}
},
data() {
return {
modal: false,
readPath: "",
loading: {
upload: false
}
};
},
watch: {
url(n) {
this.readPath = n;
}
},
methods: {
showImg() {
this.modal = true;
},
showSelect() {
const self = this;
const fileD = document.getElementById(self.fileInputId);
fileD.click();
fileD.onchange = function() {
const fileObj = this;
if (fileObj.files.length === 0) {
return null;
} else {
const form = new FormData();
form.append("file", fileObj.files[0]);
self.loading.upload = true;
self
.$post("/upload/image", form)
.then(res => {
if (res.code == 0) {
self.$emit("url", res.data[0]);
self.readPath = res.data[0];
}
})
.finally(() => {
self.loading.upload = false;
});
}
};
}
}
};
</script>
<style scoped>
.subtitle {
width: 600px;
position: absolute;
color: #999;
}
</style>
- 頁面中匯入圖片上傳元件並註冊
import uploadImg from "@/components/component/uploadImg";
export default {
component:{uploadImg }
}
- 頁面檢視中使用
<uploadImg :url="obj1.icon" @url="obj1.icon = $event" :fileInputId="'photo'"></uploadImg>
- 效果