WebApp【公共组件库】@前端(For Git Submodule)
Tevin
2021-06-19 20ef1d98b58ac24ae7de0e40111082a382f00abf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/**
 * CImagePicker
 * @author Tevin
 */
 
<template>
    <view class="c-image-picker">
        <AtInput
            ref="input"
            :name="itemRes.name"
            :title="itemRes.label"
            :required="itemRes.required"
            :error="itemRes.error"
        />
        <AtImagePicker
            ref="picker"
            multiple
            mode="aspectFit"
            :count="9"
            :length="3"
            :files="files"
            :onChange="(files,operationType,index)=>handleChange(files,operationType,index)"
            :onFail="evt=>handleFail(evt)"
            :onImageClick="(index, file)=>handleImgView(index,file)"
        />
        <AtCurtain
            class="c-image-picker-view"
            closeBtnPosition="top-right"
            :isOpened="showImg"
            :onClose="evt=>handleImgClose()"
        >
            <image
                class="img"
                mode="aspectFit"
                :src="curtainImg"
            />
        </AtCurtain>
        <CImageCompressor ref="compressor" />
    </view>
</template>
 
<script>
import Taro from '@tarojs/taro';
import { $ } from '@tarojs/extend';
import { AtInput, AtImagePicker, AtCurtain } from 'taro-ui-vue';
import { $fetcherCommon } from '@fetchers/FCommon';
import CImageCompressor from './CImageCompressor.vue';
import './cImagePicker.scss';
 
export default {
    name: 'CImagePicker',
    components: {
        CImageCompressor,
        AtInput,
        AtImagePicker,
        AtCurtain,
    },
    props: {
        // 表单数据资源(表单组件内部机制专用)
        itemRes: Object,
    },
    data() {
        return {
            showImg: false,
            curtainImg: '',
        };
    },
    computed: {
        files() {
            const value = this.itemRes.formData[this.itemRes.name];
            let files = [];
            if (Object.prototype.toString.call(value) === '[object String]') {
                files = value.split(',').map(url => ({ url }));
            } else if (Object.prototype.toString.call(value) === '[object Array]') {
                files = value.map(url => ({ url }));
            }
            files.push({ type: 'btn' });
            return files;
        },
    },
    methods: {
        triggerChange(files) {
            const value = [];
            files.forEach(file => {
                if (file.type === 'btn') {
                    return;
                }
                value.push(file.url);
            });
            this.itemRes.onChange(value);
        },
        handleChange(files, operationType, index) {
            // 添加图片
            if (operationType === 'add') {
                const needs = files
                    .map((file, index) => {
                        const fileInfo = file.file;
                        // 没有 file 信息对象,或者不是 blob 类型
                        if (!fileInfo || fileInfo.path.indexOf('blob') < 0) {
                            return false;
                        }
                        // 尺寸小于 2M 的图片
                        if (fileInfo.size < 1 * 1024 * 1024) {
                            return false;
                        }
                        return [fileInfo, index];
                    })
                    .filter(Boolean);
                // 存在需要压缩的图片,一次性压缩
                if (needs.length > 0) {
                    const files2 = [...files];
                    const needPath = needs.map(need => need[0].path);
                    this.$refs.compressor.$compress(needPath, compressedFiles => {
                        compressedFiles.forEach((cpFile, index) => {
                            const filesIndex = needs[index][1];
                            files2[filesIndex] = {
                                url: cpFile.path,
                                file: cpFile,
                            };
                        });
                        this.triggerChange(files2);
                    });
                }
                // 不存在,直接显示
                else {
                    this.triggerChange(files);
                }
            }
            // 删除图片,直接显示
            else {
                this.triggerChange(files);
            }
        },
        handleImgView(index, file) {
            this.curtainImg = file.url;
            this.showImg = true;
        },
        handleImgClose() {
            this.showImg = false;
        },
        handleFail(msg) {
            console.log(msg);
            Taro.showToast({
                title: msg,
                icon: 'none',
                mask: true,
                duration: 2000,
            });
        },
        $uploadImage(callback) {
            const url = $fetcherCommon.getUploadImgURL();
            const uploadTeam = [];
            const imgs = [];
            this.files.forEach(file => {
                if (file.type === 'btn') {
                    return;
                }
                // blob 临时文件才上传
                if (file.url.indexOf('blob') >= 0) {
                    uploadTeam.push(
                        new Promise((resolve, reject) => {
                            Taro.uploadFile({
                                url,
                                filePath: file.url,
                                name: 'file',
                                formData: {},
                                success(res) {
                                    const res2 =
                                        typeof res.data === 'string'
                                            ? JSON.parse(res.data)
                                            : res.data;
                                    if (res2.state.code === 2000) {
                                        resolve(
                                            $fetcherCommon.transImgPath(
                                                'fix',
                                                res2.data.src
                                            )
                                        );
                                    } else {
                                        reject({ message: res2.state.msg });
                                    }
                                },
                                cancel() {
                                    reject({ message: '上传图片已取消!' });
                                },
                                fail() {
                                    reject({ message: '上传图片失败!' });
                                },
                            });
                        })
                    );
                }
                // 其他类型视为 url,忽略
                else {
                    uploadTeam.push(Promise.resolve(file.url));
                }
            });
            Promise.all(uploadTeam)
                .then(res => {
                    this.itemRes.onChange(res);
                    setTimeout(() => {
                        callback('success');
                    }, 0);
                })
                .catch(err => {
                    callback('error', err);
                });
        },
    },
    mounted() {
        if (process.env.TARO_ENV === 'h5') {
            $(this.$refs.input.$el)
                .find('.at-input__input')
                .prepend(this.$refs.picker.$el);
        } else if (process.env.TARO_ENV === 'weapp') {
            $(this.$refs.input.$el)
                .find('.at-input__container')
                .append(this.$refs.picker.$el);
        }
    },
};
</script>