|
- <!-- 通用上传组件 zhao -->
-
- <template>
- <van-uploader
- v-model="fileList"
- :multiple="multiple"
- :after-read="afterRead"
- :show-upload="showUpload"
- :deletable="deletable"
- @delete="deleteFile"
- :accept="accept || null"
- />
- </template>
-
- <script>
-
- import {commonUpload} from "@/api/sunVillage_info/fixedAssets";
-
- export default {
- name: "commonUpload",
- props: {
- name: String,
- value: { // 绑定值 字符串 ,分隔 可监听
- type: String,
- default: null,
- },
- accept: { // 上传类型限制: 默认图片, * = 任意类型
- type: String,
- },
- multiple: { // 多文件上传
- type: Boolean,
- default: false,
- },
- deletable: { // 允许删除
- type: Boolean,
- default: true,
- },
- showUpload: { // 显示上传按钮
- type: Boolean,
- default: true,
- },
- formData: { // 额外请求参数
- type: Object,
- default: function() {
- return {};
- },
- },
- file: { // 上传文件字段名
- type: String,
- default: 'file',
- },
- host: {
- type: String, // 文件地址前缀
- default: '/api',
- },
- },
- watch: {
- value: function (newVal, oldVal) {
- if(newVal != this.internalValue)
- this.setInternalValue(newVal);
- },
- },
- created() {
- this.parseValue(this.value);
- },
- data() {
- return {
- internalValue: this.value,
- fileList: [],
- pathList: [],
- };
- },
- methods: {
- setInternalValue(newVal) {
- this.parseValue(newVal);
- this.internalValue = newVal;
- },
- parseValue(data) {
- if(data)
- {
- this.pathList = data.split(',');
- }
- else
- {
- this.pathList = [];
- }
- this.fileList = this.pathList.map((x) => {
- return {
- url: this.host + x,
- };
- });
- },
- makeFormData() {
- let fd = new FormData();
- if(this.formData)
- {
- for(let k of Object.keys(this.formData))
- {
- fd.set(k, this.formData[k]);
- }
- }
- return fd;
- },
- upload(file) {
- let params1 = this.makeFormData();
- params1.append(this.file, file.file);
- return commonUpload(params1).then((resp) => {
- this.pathList.push(resp.fileName);
- this.updateInternalValue();
- this.$emit('upload', resp.fileName);
- });
- },
- afterRead(file) {
- this.$toast.loading({
- message: "上传中...",
- forbidClick: true,
- duration: 0,
- });
- // 此时可以自行将文件上传至服务器
- if (file instanceof Array) {//判断是否为数组,单张图片为array,多张为数组,数组返回true否则为false
- if(file.length > 0)
- {
- let index = 0;
- const f = () => {
- if(index >= file.length)
- return;
- let up = file[index];
- //console.log(up);
- console.log(`上传文件: ${index} -> ${up.file.name}`);
- this.upload(up).then(() => {
- index++;
- if(index < file.length)
- f();
- });
- };
- f();
- }
- } else {
- this.upload(file);
- }
- },
- deleteFile(detail){
- this.pathList.splice(detail.index,1);
- this.updateInternalValue();
- this.$emit('remove', detail.index);
- },
- updateInternalValue() {
- let files = this.pathList.join(',');
- console.log(files);
- this.internalValue = files;
- if(this.internalValue != this.value)
- this.$emit('input', this.internalValue);
- },
- },
- }
- </script>
-
- <style scoped>
-
- </style>
|