micro_mall_xcx/components/upload/index.js
2023-06-15 15:16:42 +08:00

113 lines
2.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// components/upload/index.js
import { ServerBasePath } from '~/services/_utils/request'
Component({
/**
* 组件的属性列表
*/
properties: {
mediaType: {
type: Array,
value: ['image'],
},
max: {
type: Number,
value: 1,
},
lable: {
type: String,
value: "",
},
fileList: {
type: Array,
value: [],
},
},
/**
* 组件的初始数据
*/
data: {
fileList: []
},
/**
* 组件的方法列表
*/
methods: {
// 子组件中触发自定义事件并传递数据
// triggerEventToParent() {
// const dataToPass = this.data.fileList; // 获取要传递的值
// this.triggerEvent('customEvent', dataToPass); // 触发自定义事件,并传递值
// },
handleAdd(e) {
const {
fileList
} = this.data;
const {
files
} = e.detail;
// 方法1选择完所有图片之后统一上传因此选择完就直接展示
// this.setData({
// fileList: [...fileList, ...files], // 此时设置了 fileList 之后才会展示选择的图片
// });
// 方法2每次选择图片都上传展示每次上传图片的进度
files.forEach(file => this.onUpload(file))
},
onUpload(file) {
const {
fileList
} = this.data;
this.setData({
fileList: [...fileList, {
...file,
status: 'loading'
}],
});
const {
length
} = fileList;
const task = wx.uploadFile({
url: ServerBasePath + '/Common/UploadFile', // 仅为示例,非真实的接口地址
filePath: file.url,
name: 'file',
formData: {
fileDir: 'Shops'
},
success: (res) => {
this.setData({
[`fileList[${length}].url`]: JSON.parse(res.data).data.url,
[`fileList[${length}].status`]: 'done',
});
// this.triggerEventToParent()
},
});
task.onProgressUpdate((res) => {
this.setData({
[`fileList[${length}].percent`]: res.progress,
});
});
},
handleRemove(e) {
const {
index
} = e.detail;
const {
fileList
} = this.data;
fileList.splice(index, 1);
this.setData({
fileList,
});
},
}
})