<template>
<div class="update">
<!-- 通過input獲取文件 你辣,為了美觀使用v-show="false" 將input隱藏 通過input的change事件綁定fileChange-->
<input type="file" v-show="false" accept="image" ref="input" @change="fileChange($event.target.files)">
<!-- 通過$refs操作input的點擊事件嗦嗡,調(diào)起文件選擇 -->
<div @click="$refs.input.click()">
<!-- 通過slot內(nèi)容分發(fā)將頭像的顯示交給父組件,父組件可以自定義圖片樣式 -->
<slot></slot>
</div>
</div>
</template>
<script>
/*
auth:袁
作用:文件上傳
返回事件: file
返回事件參數(shù): file對象
*/
export default {
methods: {
fileChange(files) {
/* 通過FormData對象可以組裝一組用 XMLHttpRequest發(fā)送請求的鍵/值對。
它可以更靈活方便的發(fā)送表單數(shù)據(jù)届宠,因為可以獨立于表單使用。如果你把表單
的編碼類型設(shè)置為multipart/form-data ,則通過FormData傳輸?shù)臄?shù)據(jù)格式
和表單通過submit() 方法傳輸?shù)臄?shù)據(jù)格式相同*/
// 你可以自己創(chuàng)建一個FormData對象右蒲,然后通過調(diào)用它的append()方法添加字段阀湿,就像這樣:
let formData = new FormData();
formData.append('thumb', files[0]);
//由于我的請求接口需要openid所以需要再次向FormData對象添加openid字段,如果你們不需要可以不用此操作
formData.append('openid', localStorage.getItem('openid'));
// 向父組件傳遞參數(shù)瑰妄,事件為fileChange陷嘴,參數(shù)為formData對象
this.$emit('fileChange', formData)
},
}
}
</script>
組件使用
1.導(dǎo)入注冊
import Update from '@/components/update'
在 對象局部注冊該組件 components: {
Update,
},
2.頁面使用
< !--父組件通過fileChange事件用于接收子組件的派發(fā)事件 -->
<Update @fileChange="fileChange" >
<!--這里是slot自定義內(nèi)容 -->
<img :src="img" alt="" class="info">
</Update>
3.事件處理
fileChange(file) {
// 因為file是個FormData格式的對象所以可以直接通過接口開始上傳,不需要做多余操作
this.axios.post('/upload/thumb', file).then(res => {
console.log(res.data.datas)
this.img = this.HTTP + res.data.datas
}, err => {
console.log(err)
})
},