1、在element 的基礎上做一個 圖片上傳功能:
<template>
<div>
<!-- list-type 圖片的顯示類型 -->
<!-- action 圖片要上次服務器的地址 -->
<!-- on-preview 點擊文件列表中已上傳的文件時的觸發的鈎子函數(點擊顯示對應的預覽圖片) -->
<!-- on-remove 點擊刪除圖片的時候觸發的鈎子函數 -->
<!-- headers 上傳可能需要攜帶的請求頭部參數(不需要可以不加) -->
<el-upload
:action="uploadURL"
:on-preview="handlePreview"
:on-remove="handleRemove"
:headers="headerObj"
:on-success="handleSuccess"
list-type="picture"
>
<el-button size="small" type="primary">點擊上傳</el-button>
</el-upload>
<!-- 圖片預覽彈框 -->
<el-dialog title="圖片預覽" :visible.sync="previewDialogVisible" width="40%" class="dialog-picture" >
<img :src="picPreviewPath" alt="" class="previewImg" />
</el-dialog>
</div>
</template>
<script>
export default {
name: "Params",
data() {
return {
// 圖片上傳地址
uploadURL: "http://timemeetyou.com:8889/api/private/v1/upload",
// 圖片上傳組件的請求對象
headerObj: {
Authorization: localStorage.getItem("token"),
},
//定義一個數組來存放路徑
pictureList: [],
//預覽的圖片路徑
picPreviewPath: null,
//預覽圖片彈框的狀態(默認關閉)
previewDialogVisible: false,
};
},
methods: {
// 監聽圖片上傳成功事件
handleSuccess(response) {
//返回的對象
// console.log(response)
//這是本地的圖片路徑
// console.log(response.data.url)
//得到一個圖片信息對象 臨時路徑
const picInfo = { pic: response.data.tmp_path };
// 將圖片信息對象,push到pictureList數組中
this.pictureList.push(picInfo);
},
//點擊圖片,利用彈框顯示出預覽圖
handlePreview(file) {
console.log("你點擊了圖片");
//console.log(file)
//獲取到本地圖片路徑
this.picPreviewPath = file.response.data.url;
//顯示出對應的預覽圖片
this.previewDialogVisible = true;
},
handleRemove(file) {
console.log("你刪除了圖片");
// 1.獲取將要刪除圖片的臨時路徑
const filePath = file.response.data.tmp_path;
// 2.從pictureList數組中,找到圖片對應的索引值
const i = this.pictureList.findIndex((x) => x.pic === filePath);
// 3.調用splice方法,移除圖片信息
this.pictureList.splice(i, 1);
console.log("刪除后的" + this.pictureList);
},
},
};
</script>
<style lang="less" scoped>
.dialog-picture {
text-align: center;
}
.previewImg {
width: 56%;
}
</style>
