參考[官網對應鏈接] (https://youzan.github.io/vant/#/zh-CN/uploader)可查看具體使用方法
1、按照官網方法引入對應的組件
import Vue from 'vue';
import { Uploader } from 'vant';
Vue.use(Uploader);
2、直接使用基礎用法
模塊
<van-uploader :after-read="afterRead" />
export default {
methods: {
afterRead(file) {
// 此時可以自行將文件上傳至服務器
console.log(file);
},
},
};
3、在上傳完成后我們需要獲取文件對象並上傳至服務器,此處利用的是after-read屬性完成,
獲取對象之后轉為Formdata,接着調用接口上傳,注意,目標對象是file.file一般情況下后台會返回圖片地址,此時我們就可以引用了
完整代碼如下
<van-uploader :after-read="afterRead" />
export default {
methods: {
async afterRead (file) {
const fd = new FormData()
fd.append('file', file.file)
const res = await upload(fd)
this.userInfo.head_img = this.$axios.defaults.baseURL + res.data.data.url
// console.log(file.file.name)
console.log(res)
}
},
};