增强办公

This commit is contained in:
2026-04-17 12:09:43 +08:00
parent e76028bf43
commit a026ef7a54
10 changed files with 2354 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
<template>
<view v-if="visible" class="mask" @tap="close">
<view class="sheet" @tap.stop>
<view class="sheet-header">
<text class="sheet-title">选择目的地</text>
<text class="sheet-close" @tap="close">关闭</text>
</view>
<view class="city-path">{{ pathLabel || '请选择目的地' }}</view>
<picker-view class="wheel" :value="pickerValue" @change="onChange">
<picker-view-column>
<view v-for="item in continents" :key="item.name" class="wheel-item"><text>{{ item.name }}</text></view>
</picker-view-column>
<picker-view-column>
<view v-for="item in countries" :key="item.name" class="wheel-item"><text>{{ item.name }}</text></view>
</picker-view-column>
<picker-view-column>
<view v-for="item in cities" :key="item" class="wheel-item"><text>{{ item }}</text></view>
</picker-view-column>
</picker-view>
<view class="footer">
<button class="btn ghost" @tap="close">取消</button>
<button class="btn primary" @tap="confirm">确定</button>
</view>
</view>
</view>
</template>
<script>
const CITY_DATA = [
{ name: '亚洲', countries: [{ name: '中国', cities: ['北京', '上海', '广州', '深圳', '杭州', '成都'] }, { name: '日本', cities: ['东京', '大阪', '京都'] }, { name: '韩国', cities: ['首尔', '釜山'] }, { name: '新加坡', cities: ['新加坡'] }] },
{ name: '欧洲', countries: [{ name: '英国', cities: ['伦敦', '曼彻斯特'] }, { name: '法国', cities: ['巴黎', '里昂'] }, { name: '德国', cities: ['柏林', '慕尼黑'] }] },
{ name: '北美洲', countries: [{ name: '美国', cities: ['纽约', '洛杉矶', '旧金山'] }, { name: '加拿大', cities: ['多伦多', '温哥华'] }] },
{ name: '大洋洲', countries: [{ name: '澳大利亚', cities: ['悉尼', '墨尔本'] }, { name: '新西兰', cities: ['奥克兰', '惠灵顿'] }] }
]
export default {
props: { visible: Boolean, value: String },
emits: ['update:visible', 'change'],
data() { return { pickerValue: [0, 0, 0], cityData: CITY_DATA } },
computed: {
continents() { return this.cityData },
countries() { return this.continents[this.pickerValue[0]]?.countries || [] },
cities() { return this.countries[this.pickerValue[1]]?.cities || [] },
pathLabel() { const a = this.continents[this.pickerValue[0]]?.name || ''; const b = this.countries[this.pickerValue[1]]?.name || ''; const c = this.cities[this.pickerValue[2]] || ''; return [a,b,c].filter(Boolean).join(' / ') }
},
watch: { visible(v) { if (v) this.initValue() } },
methods: {
initValue() { this.pickerValue = [0,0,0] },
onChange(e) { this.pickerValue = (e.detail.value || []).map(v => Number(v)) },
confirm() { this.$emit('change', this.pathLabel); this.close() },
close() { this.$emit('update:visible', false) }
}
}
</script>
<style scoped>
.mask{position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:1000;display:flex;align-items:flex-end}.sheet{width:100%;background:#fff;border-radius:24rpx 24rpx 0 0;padding:20rpx;box-sizing:border-box}.sheet-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:16rpx}.sheet-title{font-size:30rpx;font-weight:800}.sheet-close{font-size:26rpx;color:#1677ff}.city-path{padding:12rpx 16rpx;margin-bottom:12rpx;border-radius:16rpx;background:#f8fafc;color:#334155;font-size:24rpx}.wheel{height:520rpx}.wheel-item{display:flex;align-items:center;justify-content:center;height:88rpx}.footer{display:flex;gap:12rpx;margin-top:16rpx}.btn{flex:1;border-radius:16rpx}.btn.ghost{background:#f3f4f6;color:#334155}.btn.primary{background:#1677ff;color:#fff}
</style>

View File

@@ -0,0 +1,70 @@
<template>
<view v-if="visible" class="mask" @tap="close">
<view class="sheet" @tap.stop>
<view class="sheet-header">
<text class="sheet-title">选择时间</text>
<text class="sheet-close" @tap="close">关闭</text>
</view>
<picker-view ref="picker" class="wheel" @change="onChange">
<picker-view-column>
<view v-for="(d, i) in dateOptions" :key="d" class="wheel-item"><text>{{ d }}</text></view>
</picker-view-column>
<picker-view-column>
<view v-for="(h, i) in hourOptions" :key="h" class="wheel-item"><text>{{ h }}</text></view>
</picker-view-column>
</picker-view>
<view class="footer">
<button class="btn ghost" @tap="close">取消</button>
<button class="btn primary" @tap="confirm">确定</button>
</view>
</view>
</view>
</template>
<script>
export default {
props: { visible: Boolean, value: String },
emits: ['update:visible', 'change'],
data() { return { pickerValue: [0, 0], days: 30 } },
computed: {
dateOptions() { const res = []; const base = new Date(); base.setHours(0,0,0,0); for (let i = 0; i < this.days; i++) { const d = new Date(base); d.setDate(d.getDate() + i); res.push(this.formatYMD(d)) } return res },
hourOptions() { return Array.from({ length: 24 }, (_, i) => `${i < 10 ? '0' : ''}${i}`) }
},
watch: {
visible(v) { if (v) setTimeout(() => this.initValue(), 100) }
},
methods: {
initValue() {
if (this.value) {
const v = String(this.value).replace('T', ' ')
const parts = v.split(' ')
const ymd = parts[0].split('-')
const hm = parts[1]?.split(':') || [0, 0]
const hour = parseInt(hm[0]) || 0
const dateIndex = this.dateOptions.indexOf(ymd.join('-'))
this.pickerValue = [dateIndex >= 0 ? dateIndex : 0, hour]
} else {
this.pickerValue = [0, 0]
}
this.$nextTick(() => {
const pv = this.$refs.picker
if (pv) pv.setValue(this.pickerValue)
})
},
onChange(e) { this.pickerValue = e.detail.value },
confirm() {
const date = this.dateOptions[this.pickerValue[0]] || this.dateOptions[0]
let hour = this.pickerValue[1] || 0
if (hour >= 24) hour = 23
this.$emit('change', `${date}T${hour < 10 ? '0' : ''}${hour}:00:00.000+08:00`)
this.close()
},
close() { this.$emit('update:visible', false) },
formatYMD(d) { const p = n => (n < 10 ? `0${n}` : n); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}` }
}
}
</script>
<style scoped>
.mask{position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:1000;display:flex;align-items:flex-end}.sheet{width:100%;background:#fff;border-radius:24rpx 24rpx 0 0;padding:20rpx;box-sizing:border-box}.sheet-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:16rpx}.sheet-title{font-size:30rpx;font-weight:800}.sheet-close{font-size:26rpx;color:#1677ff}.wheel{height:520rpx}.wheel-item{display:flex;align-items:center;justify-content:center;height:88rpx}.footer{display:flex;gap:12rpx;margin-top:16rpx}.btn{flex:1;border-radius:16rpx}.btn.ghost{background:#f3f4f6;color:#334155}.btn.primary{background:#1677ff;color:#fff}
</style>

View File

@@ -0,0 +1,72 @@
<template>
<view v-if="visible" class="mask" @tap="close">
<view class="sheet" @tap.stop>
<view class="sheet-header">
<text class="sheet-title">{{ title }}</text>
<text class="sheet-close" @tap="close">关闭</text>
</view>
<input class="search" v-model="keyword" placeholder="搜索姓名/部门" />
<scroll-view class="list" scroll-y>
<view v-for="item in filteredList" :key="item.userId || item.id" class="list-item" @tap="select(item)">
<view class="list-main">
<view class="list-name">{{ getName(item) }}</view>
<view class="list-sub">{{ getDept(item) }}</view>
</view>
<view class="check" :class="isSelected(item) ? 'selected' : ''"></view>
</view>
</scroll-view>
<view class="footer">
<button class="btn ghost" @tap="close">取消</button>
<button v-if="multiple" class="btn primary" @tap="confirm">确定</button>
</view>
</view>
</view>
</template>
<script>
export default {
props: {
visible: Boolean,
title: { type: String, default: '选择人员' },
list: { type: Array, default: () => [] },
multiple: { type: Boolean, default: false },
value: { type: [Object, Array, null], default: null }
},
emits: ['update:visible', 'change', 'confirm'],
data() { return { keyword: '' } },
computed: {
filteredList() {
const kw = this.keyword.trim().toLowerCase()
if (!kw) return this.list
return this.list.filter(item => `${this.getName(item)} ${this.getDept(item)}`.toLowerCase().includes(kw))
}
},
methods: {
getName(item) { return item?.empName || item?.nickName || item?.userName || item?.realName || `员工${item?.userId || item?.id || ''}` },
getDept(item) { return item?.dept?.deptName || item?.deptName || '未分配部门' },
isSelected(item) {
if (!this.multiple) return this.value && String((this.value.userId || this.value.id)) === String(item.userId || item.id)
return Array.isArray(this.value) && this.value.some(v => String((v.userId || v.id)) === String(item.userId || item.id))
},
select(item) {
if (this.multiple) {
const arr = Array.isArray(this.value) ? [...this.value] : []
const id = String(item.userId || item.id)
const idx = arr.findIndex(v => String(v.userId || v.id) === id)
if (idx >= 0) arr.splice(idx, 1)
else arr.push(item)
this.$emit('change', arr)
return
}
this.$emit('change', item)
this.close()
},
confirm() { this.$emit('confirm'); this.close() },
close() { this.$emit('update:visible', false) }
}
}
</script>
<style scoped>
.mask{position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:1000;display:flex;align-items:flex-end}.sheet{width:100%;background:#fff;border-radius:24rpx 24rpx 0 0;padding:20rpx;box-sizing:border-box}.sheet-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:16rpx}.sheet-title{font-size:30rpx;font-weight:800}.sheet-close{font-size:26rpx;color:#1677ff}.search{width:100%;box-sizing:border-box;padding:18rpx 20rpx;border:1rpx solid #e5e7eb;border-radius:16rpx;background:#f9fafb;font-size:26rpx;margin-bottom:16rpx}.list{max-height:60vh}.list-item{display:flex;justify-content:space-between;align-items:center;padding:18rpx 4rpx;border-bottom:1rpx solid #f3f4f6}.list-name{font-size:28rpx;font-weight:700}.list-sub{font-size:22rpx;color:#94a3b8;margin-top:4rpx}.check{width:28rpx;height:28rpx;border-radius:50%;border:2rpx solid #cbd5e1}.check.selected{background:#1677ff;border-color:#1677ff}.footer{display:flex;gap:12rpx;margin-top:16rpx}.btn{flex:1;border-radius:16rpx}.btn.ghost{background:#f3f4f6;color:#334155}.btn.primary{background:#1677ff;color:#fff}
</style>

View File

@@ -0,0 +1,152 @@
<template>
<view v-if="visible" class="picker-mask" @tap="close">
<view class="picker-sheet" @tap.stop>
<view class="picker-header">
<text class="picker-title">选择目的地</text>
<text class="picker-close" @tap="close">关闭</text>
</view>
<view class="city-path">{{ currentPath }}</view>
<picker-view class="city-wheel" :value="wheelValue" @change="onChange">
<picker-view-column>
<view class="wheel-item" v-for="item in continents" :key="item.name">
<view class="wheel-value">{{ item.name }}</view>
</view>
</picker-view-column>
<picker-view-column>
<view class="wheel-item" v-for="item in currentCountries" :key="item.name">
<view class="wheel-value">{{ item.name }}</view>
</view>
</picker-view-column>
<picker-view-column>
<view class="wheel-item" v-for="item in currentCities" :key="item.name">
<view class="wheel-value">{{ item.name }}</view>
</view>
</picker-view-column>
</picker-view>
<view class="picker-footer">
<button class="btn ghost" @tap="close">取消</button>
<button class="btn primary" @tap="confirm">确定</button>
</view>
</view>
</view>
</template>
<script>
const CITY_DATA = [
{ name: '亚洲', countries: [
{ name: '中国', cities: ['北京', '上海', '广州', '深圳', '杭州', '成都', '重庆', '西安', '南京', '武汉'] },
{ name: '日本', cities: ['东京', '大阪', '京都', '名古屋', '横滨'] },
{ name: '韩国', cities: ['首尔', '釜山', '仁川'] },
{ name: '新加坡', cities: ['新加坡'] },
{ name: '泰国', cities: ['曼谷', '清迈', '普吉'] },
{ name: '马来西亚', cities: ['吉隆坡', '槟城', '新山'] },
{ name: '印度', cities: ['新德里', '孟买', '班加罗尔'] },
{ name: '阿联酋', cities: ['迪拜', '阿布扎比'] }
]},
{ name: '欧洲', countries: [
{ name: '英国', cities: ['伦敦', '曼彻斯特', '伯明翰'] },
{ name: '法国', cities: ['巴黎', '里昂', '马赛'] },
{ name: '德国', cities: ['柏林', '慕尼黑', '法兰克福'] },
{ name: '意大利', cities: ['罗马', '米兰', '威尼斯'] },
{ name: '西班牙', cities: ['马德里', '巴塞罗那', '瓦伦西亚'] },
{ name: '荷兰', cities: ['阿姆斯特丹', '鹿特丹'] }
]},
{ name: '北美洲', countries: [
{ name: '美国', cities: ['纽约', '洛杉矶', '旧金山', '芝加哥', '西雅图'] },
{ name: '加拿大', cities: ['多伦多', '温哥华', '蒙特利尔'] },
{ name: '墨西哥', cities: ['墨西哥城', '瓜达拉哈拉'] }
]},
{ name: '南美洲', countries: [
{ name: '巴西', cities: ['圣保罗', '里约热内卢', '巴西利亚'] },
{ name: '阿根廷', cities: ['布宜诺斯艾利斯', '科尔多瓦'] },
{ name: '智利', cities: ['圣地亚哥'] }
]},
{ name: '大洋洲', countries: [
{ name: '澳大利亚', cities: ['悉尼', '墨尔本', '布里斯班', '珀斯'] },
{ name: '新西兰', cities: ['奥克兰', '惠灵顿', '基督城'] }
]},
{ name: '非洲', countries: [
{ name: '埃及', cities: ['开罗', '亚历山大'] },
{ name: '南非', cities: ['约翰内斯堡', '开普敦'] },
{ name: '肯尼亚', cities: ['内罗毕'] }
]}
]
export default {
props: { visible: Boolean, value: String },
emits: ['update:visible', 'change'],
data() {
return {
wheelValue: [0, 0, 0],
data: CITY_DATA
}
},
computed: {
continents() { return this.data },
currentCountries() { return this.continents[this.wheelValue[0]]?.countries || [] },
currentCities() { return this.currentCountries[this.wheelValue[1]]?.cities?.map(name => ({ name })) || [] },
currentPath() {
const c1 = this.continents[this.wheelValue[0]]?.name || ''
const c2 = this.currentCountries[this.wheelValue[1]]?.name || ''
const c3 = this.currentCities[this.wheelValue[2]]?.name || ''
return [c1, c2, c3].filter(Boolean).join(' / ') || '请选择目的地'
}
},
watch: {
visible(val) {
if (val) this.initFromValue()
},
wheelValue() {
this.normalize()
}
},
methods: {
initFromValue() {
const target = String(this.value || '')
let found = [0, 0, 0]
this.data.forEach((continent, i) => {
continent.countries.forEach((country, j) => {
country.cities.forEach((city, k) => {
const full = `${continent.name}/${country.name}/${city}`
if (target === full || target === city) found = [i, j, k]
})
})
})
this.wheelValue = found
},
normalize() {
const c = this.continents[this.wheelValue[0]]
if (!c) return
if (this.wheelValue[1] >= c.countries.length) this.wheelValue[1] = 0
const country = c.countries[this.wheelValue[1]]
if (!country) return
if (this.wheelValue[2] >= country.cities.length) this.wheelValue[2] = 0
},
onChange(e) {
this.wheelValue = (e.detail.value || []).map(v => Number(v))
},
confirm() {
const continent = this.continents[this.wheelValue[0]]
const country = this.currentCountries[this.wheelValue[1]]
const city = this.currentCities[this.wheelValue[2]]
const payload = {
continent: continent?.name || '',
country: country?.name || '',
city: city?.name || '',
label: [continent?.name, country?.name, city?.name].filter(Boolean).join(' / '),
value: [continent?.name, country?.name, city?.name].filter(Boolean).join('/')
}
this.$emit('change', payload)
this.$emit('update:visible', false)
},
close() { this.$emit('update:visible', false) }
}
}
</script>
<style scoped>
.picker-mask{position:fixed;inset:0;background:rgba(15,23,42,.45);z-index:1000;display:flex;align-items:flex-end}.picker-sheet{width:100%;background:#fff;border-radius:24rpx 24rpx 0 0;padding:20rpx;box-sizing:border-box}.picker-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:16rpx}.picker-title{font-size:30rpx;font-weight:800;color:#111827}.picker-close{font-size:26rpx;color:#1677ff}.city-path{padding:12rpx 16rpx;margin-bottom:12rpx;border-radius:16rpx;background:#f8fafc;color:#334155;font-size:24rpx}.city-wheel{height:520rpx;display:flex}.wheel-item{display:flex;align-items:center;justify-content:center;height:88rpx}.wheel-value{font-size:28rpx;font-weight:600;color:#111827}.picker-footer{display:flex;gap:12rpx;margin-top:16rpx}.btn{flex:1;border-radius:16rpx}.btn.ghost{background:#f3f4f6;color:#334155}.btn.primary{background:linear-gradient(135deg,#1677ff,#4f9dff);color:#fff}
</style>

View File

@@ -0,0 +1,166 @@
<template>
<view class="page">
<scroll-view class="scroll" scroll-y>
<view class="card" v-for="section in sections" :key="section.key">
<view class="card-title">{{ section.title }}</view>
<view v-for="field in section.fields" :key="field.key" class="field">
<text class="label">{{ field.label }}<text v-if="field.required" class="req">*</text></text>
<template v-if="field.type === 'select'"><picker mode="selector" :range="field.options" @change="e => onSelect(field.key, field.options, e)"><view class="input-like clickable">{{ form[field.key] || field.placeholder }}</view></picker></template>
<template v-else-if="field.type === 'datetime'"><view class="input-like clickable" @tap="openDateTime(field.key)">{{ formatDateTime(field.key) || field.placeholder }}</view></template>
<template v-else-if="field.type === 'city'"><view class="input-like clickable" @tap="openCity(field.key)">{{ form[field.key] || field.placeholder }}</view></template>
<template v-else-if="field.type === 'computed'"><view class="computed-box">{{ computedFieldText(field.key) || field.placeholder || '' }}</view></template>
<template v-else-if="field.type === 'file'">
<view class="file-picker-wrap">
<view class="upload-box clickable" @tap="openFilePicker(field.key)">
<view class="upload-hint">{{ field.placeholder || '点击上传文件' }}</view>
<view class="upload-sub">支持文件上传点击后选择文件</view>
</view>
<view class="file-list" v-if="fileFields[field.key] && fileFields[field.key].length">
<view class="file-item" v-for="(file, idx) in fileFields[field.key]" :key="file.ossId || file.url || idx">
<text class="file-name">{{ file.originalName || file.fileName || file.url }}</text>
<text class="remove" @tap="removeFile(field.key, idx)">删除</text>
</view>
</view>
</view>
</template>
<template v-else-if="field.type === 'textarea'"><textarea class="textarea" v-model="form[field.key]" :maxlength="field.maxlength || 200" :placeholder="field.placeholder" /></template>
<template v-else><input class="input" :type="field.inputType || 'text'" v-model="form[field.key]" :placeholder="field.placeholder" /></template>
</view>
</view>
<view class="card"><view class="card-title">审批方式</view><view class="field"><text class="label">审批人<text class="req">*</text></text><view class="input-like clickable" @tap="openEmployeePicker('assignee')">{{ assigneeLabel || '点击选择审批人' }}</view></view></view>
<view class="card"><view class="card-title">抄送</view><view class="field"><text class="label">抄送人</text><view class="input-like clickable" @tap="openEmployeePicker('cc')">{{ ccUsers.length ? `已选择 ${ccUsers.length} ` : '点击选择抄送人' }}</view></view></view>
<view class="card"><view class="card-title">提交</view><button class="btn primary" :loading="submitting" @tap="submit">提交申请</button></view>
</scroll-view>
<x-file-picker ref="globalFilePicker" @select="onGlobalFileSelect" />
<employee-picker :visible.sync="employeeSheetVisible" :title="employeeMode === 'assignee' ? '选择审批人' : '选择抄送人'" :list="employees" :multiple="employeeMode === 'cc'" :value="employeeMode === 'assignee' ? assignee : ccUsers" @change="onEmployeeChange" />
<date-time-picker :visible.sync="dateTimeSheetVisible" :value="form[datetimeFieldKey]" @change="onDateTimeChange" />
<city-picker :visible.sync="citySheetVisible" :value="form[cityFieldKey]" @change="onCityChange" />
</view>
</template>
<script>
import { ccFlowTask } from '@/api/hrm/flow'
import { listUser } from '@/api/oa/user'
import { getEmployeeByUserId } from '@/api/hrm/employee'
import { uploadFile } from '@/api/common/upload'
import EmployeePicker from '@/components/hrm/EmployeePicker.vue'
import DateTimePicker from '@/components/hrm/DateTimePicker.vue'
import CityPicker from '@/components/hrm/CityPicker.vue'
import XFilePicker from '@/components/x-native-uploader/x-file-picker.vue'
export default {
components: { EmployeePicker, DateTimePicker, CityPicker, XFilePicker },
props: { title: String, subtitle: String, bizType: String, requestApi: Function, initialForm: Object, sections: Array, flowFields: { type: Array, default: () => [] } },
data() { return { submitting: false, form: JSON.parse(JSON.stringify(this.initialForm || {})), employees: [], employeeSheetVisible: false, employeeMode: 'assignee', assignee: null, ccUsers: [], cachedAssigneeKey: '', dateTimeSheetVisible: false, datetimeFieldKey: '', citySheetVisible: false, cityFieldKey: '', imageFields: {}, fileFields: {}, currentEmpId: null } },
computed: { assigneeLabel() { return this.assignee ? this.employeeName(this.assignee) : '' } },
async created() {
this.cachedAssigneeKey = `hrm_manual_assignee_${this.bizType || 'default'}`;
await this.loadEmployees();
await this.loadCurrentEmpId()
this.restoreAssignee()
},
watch: {
'form.startTime'(val) { this.autoFillHours() },
'form.endTime'(val) { this.autoFillHours() }
},
methods: {
onSelect(fieldKey, options, e) {
const idx = Number(e.detail.value)
this.$set(this.form, fieldKey, options[idx])
},
employeeName(emp) { return emp?.empName || emp?.nickName || emp?.userName || emp?.realName || `员工${emp?.userId || emp?.id || ''}` },
employeeDept(emp) { return emp?.dept?.deptName || emp?.deptName || '未分配部门' },
async loadEmployees() { try { const res = await listUser({ pageNum: 1, pageSize: 500 }); this.employees = res.rows || res.data || [] } catch (e) { this.employees = [] } },
async loadCurrentEmpId() { try { const oaId = uni.getStorageSync('oaId'); if (!oaId) return; const emp = await getEmployeeByUserId(oaId); if (emp?.data?.empId) this.currentEmpId = emp.data.empId } catch (e) { console.log('[loadCurrentEmpId] error', e) } },
restoreAssignee() { try { const raw = uni.getStorageSync(this.cachedAssigneeKey); if (!raw) return; const cached = typeof raw === 'string' ? JSON.parse(raw) : raw; const id = String(cached.userId || cached.empId || ''); const hit = this.employees.find(e => String(e.userId || e.id) === id); if (hit) this.assignee = hit } catch (e) {} },
openEmployeePicker(mode) { this.employeeMode = mode; this.employeeSheetVisible = true },
onEmployeeChange(val) { if (this.employeeMode === 'assignee') { this.assignee = val; try { uni.setStorageSync(this.cachedAssigneeKey, JSON.stringify({ userId: val.userId || val.id, empId: val.empId || '', empName: this.employeeName(val), deptName: this.employeeDept(val) })) } catch (e) {} } else { this.ccUsers = val || [] } },
openFilePicker(fieldKey) {
this.currentFileFieldKey = fieldKey
console.log('[RequestForm] openFilePicker', fieldKey, this.$refs.globalFilePicker)
const picker = this.$refs.globalFilePicker
if (picker && picker.open) {
picker.open()
} else {
console.warn('[RequestForm] file picker ref missing or open() unavailable,', fieldKey, picker)
}
},
async onGlobalFileSelect(payload) {
const fieldKey = this.currentFileFieldKey
console.log('[RequestForm] file select', fieldKey, payload)
if (!fieldKey) return
const files = Array.isArray(payload) ? payload : [payload]
if (!this.fileFields[fieldKey]) this.$set(this.fileFields, fieldKey, [])
for (const f of files.filter(Boolean)) {
try {
const uploaded = await uploadFile({
path: f.path || f.url || '',
name: f.name || f.fileName || 'file',
size: f.size || 0,
type: f.type || ''
})
this.fileFields[fieldKey].push({
name: uploaded.fileName || f.name || f.fileName || 'file',
extname: (f.name || f.fileName || '').split('.').pop() || '',
url: uploaded.url || f.path || f.url || '',
ossId: uploaded.ossId || uploaded.url || f.path || f.url || '',
fileName: uploaded.fileName || f.fileName || f.name || '',
originalName: f.name || f.fileName || uploaded.fileName || ''
})
} catch (e) {
uni.showToast({ title: e.message || '上传失败', icon: 'none' })
}
}
this.$set(this.form, fieldKey, this.fileFields[fieldKey].map(x => x.ossId).join(','))
this.currentFileFieldKey = ''
},
removeFile(fieldKey, idx) { const arr = (this.fileFields[fieldKey] || []).slice(); arr.splice(idx, 1); this.$set(this.fileFields, fieldKey, arr); this.$set(this.form, fieldKey, arr.map(x => x.ossId).join(',')) },
openDateTime(fieldKey) { this.datetimeFieldKey = fieldKey; this.dateTimeSheetVisible = true },
formatDateTime(key) { const v = this.form[key]; if (!v) return ''; return v.replace('T', ' ').substring(0, 16) },
onDateTimeChange(val) { if (!this.datetimeFieldKey) return; this.$set(this.form, this.datetimeFieldKey, val); this.autoFillHours() },
computedFieldText(key) { if (key === 'hours') { const val = this.form[key]; return val ? `${val} 小时` : '' } return this.form[key] || '' },
openCity(fieldKey) { this.cityFieldKey = fieldKey; this.citySheetVisible = true },
onCityChange(val) { if (!this.cityFieldKey) return; this.$set(this.form, this.cityFieldKey, val) },
onFileSelect(fieldKey) { if (!this.fileFields[fieldKey]) this.$set(this.fileFields, fieldKey, []) },
onFileSuccess(fieldKey, e) {
if (!this.fileFields[fieldKey]) this.$set(this.fileFields, fieldKey, [])
const files = e?.tempFiles || []
const current = Array.isArray(this.fileFields[fieldKey]) ? this.fileFields[fieldKey] : []
this.fileFields[fieldKey] = [...current, ...files.map(f => ({
name: f.name || f.fileName || 'file',
extname: (f.name || f.fileName || '').split('.').pop() || '',
url: f.url || f.tempFilePath || f.path || '',
ossId: f.ossId || f.fileID || f.url || '',
fileName: f.fileName || f.name || '',
originalName: f.originalName || f.name || f.fileName || ''
}))]
this.$set(this.form, fieldKey, this.fileFields[fieldKey].map(x => x.ossId).join(','))
},
onFileDelete(fieldKey, e) {
const fileList = Array.isArray(this.fileFields[fieldKey]) ? this.fileFields[fieldKey] : []
const index = e?.index ?? e?.indexs?.[0] ?? -1
if (index >= 0) fileList.splice(index, 1)
this.$set(this.fileFields, fieldKey, [...fileList])
this.$set(this.form, fieldKey, fileList.map(x => x.ossId).join(','))
},
pickImages() {},
autoFillHours() {
const s = this.parseDT(this.form.startTime), e = this.parseDT(this.form.endTime)
if (!s || !e) return;
const ms = e.getTime() - s.getTime();
if (ms <= 0) return;
const hours = (Math.round((ms / 3600000) * 2) / 2).toFixed(1).replace(/\.0$/, '');
this.$set(this.form, 'hours', hours)
},
parseDT(v) { if (!v) return null; const d = new Date(String(v).replace('T', ' ').replace(/-/g, '/')); return Number.isNaN(d.getTime()) ? null : d },
submit() { this.autoFillHours(); for (const f of this.flowFields) if (f.required && !this.form[f.key]) return uni.showToast({ title: `请填写${f.label}`, icon: 'none' }); if (!this.assignee) return uni.showToast({ title: '请选择审批人', icon: 'none' }); this.doSubmit() },
async doSubmit() { this.submitting = true; try { const payload = { ...this.form, status: 'pending', empId: this.currentEmpId, manualAssigneeUserId: this.assignee.userId || this.assignee.id }; const res = await this.requestApi(payload); const inst = res?.data || res; if (this.ccUsers.length && inst?.instId) await ccFlowTask({ instId: inst.instId, bizId: inst.bizId, bizType: this.bizType, ccUserIds: this.ccUsers.map(u => u.userId || u.id), remark: '手机端抄送', fromUserId: this.$store?.state?.user?.id || '', nodeId: 0, nodeName: '节点#0', readFlag: 0 }); uni.showToast({ title: '提交成功', icon: 'success' }); setTimeout(() => uni.navigateBack({ delta: 1 }), 500) } catch (e) { uni.showToast({ title: e.message || '提交失败', icon: 'none' }) } finally { this.submitting = false } }
}
}
</script>
<style scoped>
.page{min-height:100vh;background:#f5f7fb}.scroll{height:100vh;padding:24rpx;box-sizing:border-box}.card{background:#fff;border-radius:20rpx;padding:24rpx;margin-bottom:20rpx}.card-title{font-size:30rpx;font-weight:700;color:#111827;margin-bottom:16rpx}.field{margin-bottom:18rpx}.label{display:block;margin-bottom:8rpx;font-size:24rpx;color:#6b7280}.req{color:#ef4444;margin-left:4rpx}.input-like,.input,.textarea{width:100%;box-sizing:border-box;border:1rpx solid #e5e7eb;border-radius:16rpx;background:#f9fafb;padding:20rpx;font-size:28rpx;color:#111827}.clickable{color:#111827}.textarea{min-height:160rpx}.computed-box{width:100%;box-sizing:border-box;padding:18rpx 20rpx;border-radius:16rpx;background:#eef6ff;color:#6b8fd6;font-size:26rpx;font-weight:500;line-height:1.5}.upload-box{border:1rpx dashed #cbd5e1;border-radius:18rpx;background:linear-gradient(180deg,#fbfdff 0%,#f4f8ff 100%);padding:24rpx 22rpx;box-shadow:0 8rpx 24rpx rgba(22,119,255,.06);}.upload-hint{font-size:28rpx;color:#111827;font-weight:700}.upload-sub{margin-top:8rpx;font-size:22rpx;color:#94a3b8;line-height:1.5}.file-list{margin-top:16rpx;display:flex;flex-direction:column;gap:12rpx}.file-item{display:flex;align-items:center;justify-content:space-between;padding:18rpx 18rpx;border-radius:16rpx;background:#f8fafc;border:1rpx solid #e5eefc}.file-name{flex:1;font-size:26rpx;color:#334155;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-right:16rpx}.remove{font-size:24rpx;color:#ef4444;flex-shrink:0}.btn.primary{width:100%;background:#1677ff;color:#fff;border-radius:16rpx}
</style>

View File

@@ -0,0 +1,316 @@
<template>
<view class="x-coupon" :style="[couponStyle]" @click="handleClick">
<!-- 左侧面值区域 -->
<view class="x-coupon__left">
<view class="x-coupon__value-box">
<text class="x-coupon__currency" v-if="type === 'money'">{{ currency }}</text>
<text class="x-coupon__value">{{ value }}</text>
<text class="x-coupon__currency" v-if="type === 'discount'"></text>
</view>
<view class="x-coupon__condition" v-if="condition">{{ condition }}</view>
</view>
<!-- 中间分割线 -->
<view class="x-coupon__divider">
<view class="x-coupon__divider-line"></view>
</view>
<!-- 右侧信息区域 -->
<view class="x-coupon__right">
<view class="x-coupon__info">
<view class="x-coupon__title">{{ title }}</view>
<view class="x-coupon__desc" v-if="desc">{{ desc }}</view>
<view class="x-coupon__validity" v-if="validity">{{ validity }}</view>
</view>
<view class="x-coupon__action">
<slot name="action">
<view class="x-coupon__btn" :class="{'x-coupon__btn--disabled': disabled}" v-if="showBtn">
{{ btnText }}
</view>
</slot>
</view>
<!-- 状态角标可选 -->
<view class="x-coupon__stamp" v-if="status !== 'available'">
<text>{{ statusText }}</text>
</view>
</view>
<!-- 上下半圆缺口 -->
<view class="x-coupon__cutout x-coupon__cutout--top" :style="{ backgroundColor: cutoutColor }"></view>
<view class="x-coupon__cutout x-coupon__cutout--bottom" :style="{ backgroundColor: cutoutColor }"></view>
</view>
</template>
<script>
export default {
name: "x-coupon",
props: {
// money 金额券 | discount 折扣券
type: {
type: String,
default: 'money'
},
value: {
type: [Number, String],
required: true
},
currency: {
type: String,
default: '¥'
},
condition: {
type: String,
default: ''
},
title: {
type: String,
default: '优惠券'
},
desc: {
type: String,
default: ''
},
validity: {
type: String,
default: ''
},
// 主题色
color: {
type: String,
default: '#ff5a5f'
},
// 卡券背景色
backgroundColor: {
type: String,
default: '#ffffff'
},
// 缺口圆的背景色(通常与页面背景一致;要透明可传 transparent
cutoutColor: {
type: String,
default: '#f5f5f5'
},
disabled: {
type: Boolean,
default: false
},
status: {
type: String,
default: 'available' // available 可用 | used 已使用 | expired 已过期
},
btnText: {
type: String,
default: '立即使用'
},
showBtn: {
type: Boolean,
default: true
}
},
computed: {
couponStyle() {
return {
'--theme-color': this.disabled ? '#cccccc' : this.color,
'--bg-color': this.backgroundColor
}
},
statusText() {
const map = {
'used': '已使用',
'expired': '已过期',
'available': ''
}
return map[this.status] || ''
}
},
methods: {
handleClick() {
if (this.disabled || this.status !== 'available') return;
this.$emit('click');
}
}
}
</script>
<style lang="scss" scoped>
.x-coupon {
position: relative;
display: flex;
align-items: stretch;
width: 100%;
height: 200rpx; // 固定高度(可按需调整)
background-color: var(--bg-color);
border-radius: 16rpx;
overflow: hidden; // 需要裁切内部溢出
box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
margin-bottom: 24rpx;
transition: all 0.3s;
&--disabled {
opacity: 0.8;
}
&__left {
width: 200rpx;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: linear-gradient(135deg, var(--theme-color), lighten(#000, 20%)); // 降级方案
background: var(--theme-color);
color: #fff;
position: relative;
padding: 20rpx;
box-sizing: border-box;
flex-shrink: 0;
// 增加轻微质感(可按需调整)
&::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(to bottom right, rgba(255,255,255,0.2), rgba(0,0,0,0.1));
pointer-events: none;
}
}
&__value-box {
display: flex;
align-items: baseline;
}
&__currency {
font-size: 24rpx;
margin-right: 4rpx;
}
&__value {
font-size: 56rpx;
font-weight: bold;
line-height: 1;
}
&__condition {
font-size: 20rpx;
margin-top: 12rpx;
opacity: 0.9;
text-align: center;
}
&__divider {
width: 0;
position: relative;
border-left: 2rpx dashed #eee;
margin-top: 20rpx;
margin-bottom: 20rpx;
z-index: 1;
}
&__right {
flex: 1;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
padding: 24rpx 30rpx 24rpx 40rpx; // 左侧预留缺口区域
position: relative;
box-sizing: border-box;
}
&__info {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
overflow: hidden;
}
&__title {
font-size: 30rpx;
font-weight: bold;
color: #333;
margin-bottom: 8rpx;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
&__desc {
font-size: 22rpx;
color: #999;
margin-bottom: 4rpx;
}
&__validity {
font-size: 20rpx;
color: #aaa;
}
&__action {
margin-left: 20rpx;
flex-shrink: 0;
display: flex;
align-items: center;
}
&__btn {
font-size: 24rpx;
padding: 8rpx 24rpx;
border-radius: 50rpx;
background-color: var(--theme-color);
color: #fff;
text-align: center;
&--disabled {
background-color: #ccc;
}
}
&__cutout {
position: absolute;
width: 30rpx;
height: 30rpx;
border-radius: 50%;
z-index: 2;
left: 185rpx; // 200rpx左侧宽度- 15rpx半径
}
&__cutout--top {
top: -15rpx;
}
&__cutout--bottom {
bottom: -15rpx;
}
&__stamp {
position: absolute;
right: 0;
top: 0;
width: 120rpx;
height: 120rpx;
overflow: hidden;
opacity: 0.6;
pointer-events: none;
text {
display: block;
width: 200rpx;
height: 40rpx;
line-height: 40rpx;
text-align: center;
background-color: #ccc;
color: #fff;
font-size: 20rpx;
transform: rotate(45deg) translate(20rpx, -20rpx);
transform-origin: center;
position: absolute;
top: 20rpx;
right: -50rpx;
}
}
}
</style>

View File

@@ -0,0 +1,110 @@
# x-coupon 优惠券组件
一个可复用的优惠券展示组件,支持金额券/折扣券、状态展示、按钮插槽、自定义主题色与缺口背景色。
## 引入方式
在页面中手动引入:
```vue
<script>
import xCoupon from '@/components/x-coupon/x-coupon.vue'
export default {
components: { xCoupon }
}
</script>
```
## 基本用法
```vue
<template>
<view style="padding: 24rpx; background: #f5f5f5;">
<x-coupon
value="100"
condition="满500可用"
title="全场通用券"
desc="仅限服饰类商品"
validity="2026.12.31 到期"
@click="onUse"
/>
</view>
</template>
<script>
import xCoupon from '@/components/x-coupon/x-coupon.vue'
export default {
components: { xCoupon },
methods: {
onUse() {
uni.showToast({ title: '使用优惠券', icon: 'none' })
}
}
}
</script>
```
## 折扣券
```vue
<x-coupon
type="discount"
value="8.5"
title="会员专享折扣"
condition="无门槛"
color="#FF9800"
/>
```
## 状态展示
```vue
<x-coupon value="50" title="新人券" status="used" disabled />
<x-coupon value="20" title="限时券" status="expired" disabled />
```
## 自定义按钮(插槽)
```vue
<x-coupon value="30" title="外卖券">
<template #action>
<view style="padding: 8rpx 22rpx; border-radius: 999rpx; background: #111; color: #fff; font-size: 24rpx;">
去使用
</view>
</template>
</x-coupon>
```
## Props
| 参数 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| type | 券类型:`money` 金额券 / `discount` 折扣券 | String | `money` |
| value | 面值(金额或折扣值) | Number \| String | 必填 |
| currency | 金额币种符号(仅 `money` 时展示) | String | `¥` |
| condition | 使用条件文案 | String | `''` |
| title | 标题 | String | `优惠券` |
| desc | 描述文案 | String | `''` |
| validity | 有效期文案 | String | `''` |
| color | 左侧主题色(也用于默认按钮色) | String | `#ff5a5f` |
| backgroundColor | 卡券背景色 | String | `#ffffff` |
| cutoutColor | 缺口圆背景色(通常传页面背景色;需要透明可传 `transparent` | String | `#f5f5f5` |
| disabled | 是否禁用点击(禁用时不会触发 click | Boolean | `false` |
| status | 状态:`available` / `used` / `expired` | String | `available` |
| btnText | 默认按钮文字(未使用 action 插槽时) | String | `立即使用` |
| showBtn | 是否显示默认按钮 | Boolean | `true` |
## Events
| 事件 | 说明 | 回调参数 |
| --- | --- | --- |
| click | 点击卡券(仅 `status=available` 且未禁用时触发) | 无 |
## Slots
| 名称 | 说明 |
| --- | --- |
| action | 右侧操作区域插槽(自定义按钮/图标等) |

View File

@@ -0,0 +1,149 @@
# x-native-uploader 原生文件上传组件
`x-native-uploader` 是一个跨平台的文件上传组件,专为解决 UniApp 在 App 端文件选择与上传的痛点而设计。它集成了 Native.js 的能力,支持在 Android 和 iOS 上调用原生文件选择器,同时兼容 H5 和小程序平台。
## 功能特性
* 📱 **原生体验**: App 端使用 Native.js 调用系统原生文件选择器 (Intent / UIDocumentPicker),支持选择任意类型文件。
* 🚀 **高性能上传**: App 端使用 `plus.uploader` 实现原生上传,支持后台传输、大文件上传,比 WebView AJAX 更稳定。
* 🔄 **跨平台兼容**: 自动降级处理H5 使用 `uni.chooseFile`,小程序使用 `uni.chooseMessageFile`,一套代码多端运行。
* 📦 **多选支持**: 支持一次选择多个文件进行批量上传 (Android/iOS/H5/MP)。
* 🛠️ **灵活配置**: 支持自定义上传 URL、Header、FormData 以及自定义触发按钮 UI。
* 📄 **PDF 及其他文件支持**: 完美处理 Android 平台的 `content://` URI 文件路径,确保 PDF、Word 等各种文档类型的正确上传。
## 引入组件
```javascript
import xNativeUploader from '@/components/x-native-uploader/x-native-uploader.vue';
export default {
components: {
xNativeUploader
}
}
```
## 代码演示
### 基础用法 (单选)
默认点击按钮选择单个文件并自动上传。
```html
<x-native-uploader
url="https://your-api.com/upload"
:header="{ 'Authorization': 'Bearer token' }"
:formData="{ userId: '123' }"
@success="onSuccess"
@fail="onFail"
></x-native-uploader>
```
### 多文件上传
设置 `multiple` 属性开启多选,`limit` 控制最大选择数量。
```html
<x-native-uploader
url="https://your-api.com/upload"
:multiple="true"
:limit="9"
fileType="all"
@success="onSuccess"
@fail="onFail"
>
<view class="custom-btn">
<text>点击批量上传文件</text>
</view>
</x-native-uploader>
```
### PDF 文件上传Android 兼容)
设置 `fileType="all"` 即可支持上传 PDF 文件,组件会自动处理 Android 平台的 `content://` URI 路径:
```html
<x-native-uploader
url="https://your-api.com/upload/pdf"
fileType="all"
accept="application/pdf"
@success="handlePdfUploadSuccess"
@fail="handleUploadFail"
>
<view class="upload-btn">
<text>上传 PDF 文件</text>
</view>
</x-native-uploader>
```
### 自定义触发按钮
通过默认插槽 (slot) 自定义上传按钮样式。
```html
<x-native-uploader url="...">
<button type="primary">点击上传</button>
</x-native-uploader>
```
## API
### Props
| 参数 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| `url` | 上传接口地址 (必填) | `String` | - |
| `name` | 上传文件的字段名 | `String` | `'file'` |
| `header` | 请求头对象 | `Object` | `{}` |
| `formData` | 额外的上传参数 | `Object` | `{}` |
| `fileType` | 文件选择类型,可选值: `image`, `video`, `all` | `String` | `'image'` |
| `multiple` | 是否开启多选 | `Boolean` | `false` |
| `limit` | 最大选择文件数量 (多选模式下有效) | `Number` | `9` |
| `autoUpload` | 选择文件后是否自动上传 | `Boolean` | `true` |
### Events
| 事件名 | 说明 | 回调参数 |
| --- | --- | --- |
| `success` | 上传成功时触发 | `{ file: FileObj, response: String }` |
| `fail` | 上传失败时触发 | `{ file: FileObj, error: Any }` |
| `progress` | 上传进度更新时触发 | `{ file: FileObj, progress: Number }` |
### FileObj 数据结构
```javascript
{
path: "...", // 文件本地路径
name: "...", // 文件名
progress: 100, // 上传进度 (0-100)
status: "success", // 状态: pending, uploading, success, error
statusText: "..." // 状态描述文本
}
```
## 注意事项
1. **Android 权限**: App 端需要 `READ_EXTERNAL_STORAGE``WRITE_EXTERNAL_STORAGE` 权限。
2. **iOS 配置**: iOS 端无需特殊配置,使用 `UIDocumentPickerViewController`
3. **H5 跨域**: 确保上传接口支持 CORS 跨域请求。
4. **小程序**: 微信小程序使用 `uni.chooseMessageFile`,支持从聊天记录中选择文件。
5. **Android content:// URI 处理**: 组件已自动处理 Android 系统返回的 `content://` 格式 URI包括对 `raw: `前缀的路径解析,确保 PDF、Word、Excel 等文件能够正确上传。
6. **文件格式支持**: 当 `fileType="all"` 时,支持选择任意类型文件,但上传前请确保服务器端支持该文件格式。
## 常见问题
### Q: 为什么在 Android 上选择 PDF 文件后上传失败?
**A**: 这是因为 Android 系统返回的文件路径是 `content://` 格式的 URI而不是真实的本地文件路径。本组件已经内置了对这种格式的自动解析处理确保文件能够正确上传。如果仍然遇到问题请检查
1. 是否已经正确配置了 Android 权限
2. 文件路径是否被正确解析
3. 服务器端是否支持接收该文件格式
### Q: 如何限制只能上传特定类型的文件?
**A**: 可以通过设置 `fileType` 属性来限制文件类型:
- `fileType="image"` - 仅允许选择图片
- `fileType="video"` - 仅允许选择视频
- `fileType="all"` - 允许选择所有类型文件
如果需要更精确的控制,可以结合使用 `accept` 属性,例如 `accept="application/pdf"`

View File

@@ -0,0 +1,730 @@
<template>
<view v-if="visible" class="x-file-picker-mask" @click="close">
<view class="x-file-picker-container" @click.stop>
<view class="picker-header">
<text class="back-btn" @click="goBack" v-if="canGoBack"></text>
<text class="title-text">{{ titleDisplay }}</text>
<view class="header-right"></view>
</view>
<!-- 菜单视图 -->
<view v-if="mode === 'menu'" class="menu-grid">
<view class="menu-item" @click="selectCamera">
<view class="menu-icon" style="background: #33C759;">📷</view>
<text class="menu-text">相机</text>
</view>
<view class="menu-item" @click="selectImage">
<view class="menu-icon" style="background: #FF2D55;">🖼</view>
<text class="menu-text">图库</text>
</view>
<view class="menu-item" @click="selectFileSystem">
<view class="menu-icon" style="background: #FF9500;">📁</view>
<text class="menu-text">文件管理</text>
</view>
<view class="menu-item" @click="selectVideo">
<view class="menu-icon" style="background: #5856D6;">🎥</view>
<text class="menu-text">视频</text>
</view>
<view class="menu-item" @click="browsePath('Download')">
<view class="menu-icon" style="background: #007AFF;"></view>
<text class="menu-text">下载</text>
</view>
<view class="menu-item" @click="browsePath('Documents')">
<view class="menu-icon" style="background: #AF52DE;">📄</view>
<text class="menu-text">文档</text>
</view>
<view class="menu-item" @click="browsePath('Music')">
<view class="menu-icon" style="background: #FF3B30;">🎵</view>
<text class="menu-text">音乐</text>
</view>
<view class="menu-item" @click="browsePath('Movies')">
<view class="menu-icon" style="background: #5AC8FA;">🎬</view>
<text class="menu-text">影视</text>
</view>
</view>
<!-- 文件列表视图 (作为系统API不可用时的降级方案) -->
<scroll-view v-else scroll-y class="file-list">
<view v-if="loading" class="loading-tips">加载中...</view>
<view v-else-if="fileList.length === 0" class="empty-tips">空文件夹</view>
<view
v-for="(item, index) in fileList"
:key="index"
class="file-item"
@click="handleItemClick(item)"
>
<view class="item-icon">
<text v-if="item.isDirectory" style="font-size: 24px;">📁</text>
<text v-else style="font-size: 24px;">📄</text>
</view>
<view class="item-info">
<text class="item-name">{{ item.name }}</text>
<text class="item-detail" v-if="!item.isDirectory">{{ formatSize(item.size) }}</text>
</view>
</view>
</scroll-view>
<!-- 底部取消按钮 -->
<view class="picker-footer" @click="close">
<text class="cancel-text">取消</text>
</view>
</view>
</view>
</template>
<script>
export default {
name: 'x-file-picker',
props: {
// 是否支持多选
multiple: {
type: Boolean,
default: false
},
// 最多选择数量
limit: {
type: Number,
default: 9
}
},
data() {
return {
visible: false,
mode: 'menu', // 'menu' | 'browser'
currentEntry: null,
currentPath: '',
rootPath: '',
fileList: [],
loading: false
};
},
computed: {
canGoBack() {
return this.mode === 'browser';
},
titleDisplay() {
if (this.mode === 'menu') return '选择操作';
if (!this.currentPath) return '/';
const parts = this.currentPath.split('/');
if (parts.length > 2) {
return '.../' + parts[parts.length - 1];
}
return this.currentPath;
}
},
methods: {
open() {
this.currentEntry = null;
this.currentPath = '';
this.fileList = [];
this.loading = false;
this.selectFileSystem();
},
close() {
this.visible = false;
},
// 拍照 (保留方法但不显示入口)
selectCamera() {
uni.chooseImage({
count: 1,
sourceType: ['camera'],
success: (res) => this.handleImageSuccess(res)
});
},
// 相册 (保留方法但不显示入口)
selectImage() {
uni.chooseImage({
count: 1,
sourceType: ['album'],
success: (res) => this.handleImageSuccess(res)
});
},
handleImageSuccess(res) {
const path = res.tempFilePaths[0];
let name = 'image.jpg';
if (res.tempFiles && res.tempFiles[0] && res.tempFiles[0].name) {
name = res.tempFiles[0].name;
} else {
name = path.substring(path.lastIndexOf('/') + 1);
}
this.$emit('select', { path, name });
this.close();
},
// 视频
selectVideo() {
uni.chooseVideo({
count: 1,
success: (res) => {
const path = res.tempFilePath;
let name = 'video.mp4';
if (res.tempFile && res.tempFile.name) {
name = res.tempFile.name;
} else {
name = path.substring(path.lastIndexOf('/') + 1);
}
this.$emit('select', { path, name });
this.close();
}
});
},
selectFileSystem() {
// #ifdef APP-PLUS
if (plus.os.name === 'Android') {
this.selectFileByNativeAndroid();
return;
}
if (plus.os.name === 'iOS') {
this.selectFileByNativeIOS();
return;
}
// #endif
this.browsePath('root');
},
handleFileSuccess(res) {
if (this.multiple) {
// 多选处理
const files = (res.tempFiles || []).map(file => {
let name = file.name || '';
const path = file.path || '';
if (!name && path) {
name = path.substring(path.lastIndexOf('/') + 1);
}
return { path, name: name || 'file' };
});
if (files.length === 0 && res.tempFilePaths) {
res.tempFilePaths.forEach(path => {
const name = path.substring(path.lastIndexOf('/') + 1);
files.push({ path, name });
});
}
if (files.length === 0) {
uni.showToast({ title: '未选择文件', icon: 'none' });
return;
}
this.$emit('select', files); // 返回数组
} else {
// 单选兼容处理 (返回单个对象)
const file = res.tempFiles && res.tempFiles[0] ? res.tempFiles[0] : null;
const path = (file && file.path) || (res.tempFilePaths && res.tempFilePaths[0]) || '';
let name = (file && file.name) || 'file';
if (!name && path) {
name = path.substring(path.lastIndexOf('/') + 1);
}
if (!path) {
uni.showToast({ title: '未选择文件', icon: 'none' });
return;
}
this.$emit('select', { path, name });
}
this.close();
},
selectFileByNativeAndroid() {
const main = plus.android.runtimeMainActivity();
const Intent = plus.android.importClass('android.content.Intent');
const intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType('*/*');
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (this.multiple) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
// 生成随机 requestCode (10000 ~ 50000) 避免冲突
const requestCode = 10000 + Math.floor(Math.random() * 40000);
// 保存旧的 onActivityResult 回调
const oldActivityResult = main.onActivityResult;
main.onActivityResult = (requestCodeResult, resultCode, data) => {
// 如果有旧的回调,先执行
if (oldActivityResult) {
try {
oldActivityResult(requestCodeResult, resultCode, data);
} catch (e) {
console.error('Old onActivityResult failed', e);
}
}
if (requestCodeResult !== requestCode) return;
if (resultCode !== -1 || !data) { // -1 is Activity.RESULT_OK
return;
}
// 处理多选 ClipData
let clipData = null;
try {
clipData = data.getClipData();
} catch(e) {
console.warn('getClipData failed', e);
}
console.log('Android File Picked: multiple=', this.multiple, 'clipData=', clipData);
if (clipData && this.multiple) {
let count = 0;
try {
// 尝试直接调用
count = clipData.getItemCount();
} catch (e) {
console.warn('clipData.getItemCount() failed, trying plus.android.invoke', e);
try {
// 降级尝试
count = plus.android.invoke(clipData, 'getItemCount');
} catch (e2) {
console.error('All getItemCount attempts failed', e2);
}
}
console.log('ClipData count:', count);
if (count > 0) {
const files = [];
let processedCount = 0;
for (let i = 0; i < count; i++) {
try {
// 尝试直接调用或 invoke
let item = null;
try {
item = clipData.getItemAt(i);
} catch(e) {
item = plus.android.invoke(clipData, 'getItemAt', i);
}
if (!item) throw new Error('Item is null');
let uri = null;
try {
uri = item.getUri();
} catch(e) {
uri = plus.android.invoke(item, 'getUri');
}
if (!uri) throw new Error('Uri is null');
const uriStr = uri.toString();
// 异步获取每个文件信息
this.resolveAndroidFile(main, uri, uriStr, (file) => {
files.push(file);
processedCount++;
if (processedCount === count) {
this.emitSelectFiles(files);
}
});
} catch (e) {
console.error('Process clip item failed at index ' + i, e);
processedCount++;
if (processedCount === count) {
this.emitSelectFiles(files);
}
}
}
return;
}
// 如果 count 为 0降级到单选逻辑
}
// 单选或不支持 ClipData
const uri = data.getData();
console.log('Single URI:', uri);
if (!uri) {
console.error('No data uri found');
return;
}
const uriStr = uri.toString();
this.resolveAndroidFile(main, uri, uriStr, (file) => {
console.log('Resolved single file:', file);
if (this.multiple) {
this.emitSelectFiles([file]);
} else {
this.emitSelect(file.path, file.name);
}
});
};
main.startActivityForResult(intent, requestCode);
},
resolveAndroidFile(main, uri, uriStr, callback) {
let callbackCalled = false;
const safeCallback = (res) => {
if (callbackCalled) return;
callbackCalled = true;
callback(res);
};
plus.io.resolveLocalFileSystemURL(uriStr, (entry) => {
safeCallback({ path: entry.fullPath, name: entry.name || '' });
}, (e) => {
console.log('resolveLocalFileSystemURL failed', e);
let name = this.getAndroidFileName(main, uri);
if (!name) {
try {
const path = uri.getPath();
if (path) {
const lastSlash = path.lastIndexOf('/');
if (lastSlash !== -1) {
name = decodeURIComponent(path.substring(lastSlash + 1));
}
}
} catch (e) {}
}
safeCallback({ path: uriStr, name: name || 'file' });
});
},
getAndroidFileName(main, uri) {
try {
const OpenableColumns = plus.android.importClass('android.provider.OpenableColumns');
const resolver = main.getContentResolver();
plus.android.importClass(resolver); // 确保 resolver 方法被绑定
const cursor = resolver.query(uri, null, null, null, null);
if (cursor) {
plus.android.importClass(cursor); // 确保 cursor 方法被绑定
if (cursor.moveToFirst()) {
const index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (index > -1) {
const name = cursor.getString(index);
cursor.close();
return name || '';
}
}
cursor.close();
}
} catch (e) {
console.error('getAndroidFileName error', e);
}
return '';
},
selectFileByNativeIOS() {
const UIDocumentPickerViewController = plus.ios.importClass('UIDocumentPickerViewController');
const picker = new UIDocumentPickerViewController(['public.data'], 0);
picker.allowsMultipleSelection = this.multiple;
picker.onDidPickDocumentAtURL = (url) => {
const path = plus.ios.invoke(url, 'path');
const name = this.extractName(path);
if (this.multiple) {
this.emitSelectFiles([{ path, name }]);
} else {
this.emitSelect(path, name);
}
plus.ios.deleteObject(picker);
};
picker.onDidPickDocumentsAtURLs = (urls) => {
const count = urls.count();
if (count > 0) {
if (this.multiple) {
const files = [];
for(let i=0; i<count; i++) {
const url = urls.objectAtIndex(i);
const path = plus.ios.invoke(url, 'path');
files.push({ path, name: this.extractName(path) });
}
this.emitSelectFiles(files);
} else {
const first = urls.objectAtIndex(0);
const path = plus.ios.invoke(first, 'path');
this.emitSelect(path, this.extractName(path));
}
}
plus.ios.deleteObject(picker);
};
picker.onWasCancelled = () => {
plus.ios.deleteObject(picker);
};
const current = plus.ios.currentViewController();
current.presentViewController(picker, true, null);
},
extractName(path) {
if (!path) return '';
return path.substring(path.lastIndexOf('/') + 1);
},
emitSelectFiles(files) {
if (!files || files.length === 0) {
uni.showToast({ title: '未选择文件', icon: 'none' });
return;
}
this.$emit('select', files);
this.close();
},
emitSelect(path, name) {
if (!path) {
uni.showToast({ title: '未选择文件', icon: 'none' });
return;
}
const fileName = name || this.extractName(path) || 'file';
this.$emit('select', { path, name: fileName });
this.close();
},
/**
* 浏览特定目录
* 由于标准基座不支持 uni.chooseFile这里使用 plus.io 进行降级处理
* 保持 UI 风格一致,但在应用内浏览文件
*/
browsePath(type) {
this.visible = true; // 仅在需要浏览器 UI 时显示遮罩
this.mode = 'browser';
this.loading = true;
let targetPath = '';
// #ifdef APP-PLUS
const base = '/storage/emulated/0/';
switch(type) {
case 'Download': targetPath = base + 'Download/'; break;
case 'Documents': targetPath = base + 'Documents/'; break;
case 'Music': targetPath = base + 'Music/'; break;
case 'Movies': targetPath = base + 'Movies/'; break;
case 'root': targetPath = base; break;
default: targetPath = base;
}
plus.io.resolveLocalFileSystemURL(targetPath, (entry) => {
this.rootPath = entry.fullPath;
this.readDirectory(entry);
}, (e) => {
console.error('Dir access failed', e);
if (type !== 'root') {
// 失败尝试回退到根目录
this.browsePath('root');
} else {
uni.showToast({ title: '无法访问存储', icon: 'none' });
this.mode = 'menu';
}
});
// #endif
// #ifndef APP-PLUS
uni.showToast({ title: '仅App端支持', icon: 'none' });
this.mode = 'menu';
// #endif
},
readDirectory(entry) {
this.currentEntry = entry;
this.currentPath = entry.fullPath;
this.loading = true;
this.fileList = [];
const reader = entry.createReader();
reader.readEntries((entries) => {
const list = [];
if (entries.length > 0) {
// 排序: 文件夹在前
entries.sort((a, b) => {
if (a.isDirectory && !b.isDirectory) return -1;
if (!a.isDirectory && b.isDirectory) return 1;
return a.name.localeCompare(b.name);
});
entries.forEach(item => {
if (item.name.startsWith('.')) return;
list.push({
name: item.name,
isDirectory: item.isDirectory,
fullPath: item.fullPath,
entry: item,
size: 0
});
});
}
this.fileList = list;
this.loading = false;
}, (e) => {
console.error('Read dir failed', e);
this.loading = false;
uni.showToast({ title: '读取目录失败', icon: 'none' });
});
},
handleItemClick(item) {
if (item.isDirectory) {
this.readDirectory(item.entry);
} else {
this.$emit('select', {
path: item.fullPath,
name: item.name
});
this.close();
}
},
goBack() {
if (this.currentPath === this.rootPath) {
this.mode = 'menu';
return;
}
if (!this.currentEntry) {
this.mode = 'menu';
return;
}
this.currentEntry.getParent((parentEntry) => {
this.readDirectory(parentEntry);
}, (e) => {
this.mode = 'menu';
});
},
formatSize(size) {
if (size < 1024) return size + ' B';
if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB';
return (size / 1024 / 1024).toFixed(2) + ' MB';
}
}
}
</script>
<style scoped>
.x-file-picker-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.4);
z-index: 999;
display: flex;
flex-direction: column;
justify-content: flex-end; /* 底部对齐 */
}
.x-file-picker-container {
width: 100%;
height: 60vh; /* 半屏高度 */
background: #fff;
border-top-left-radius: 20px;
border-top-right-radius: 20px;
display: flex;
flex-direction: column;
overflow: hidden;
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
}
.picker-header {
height: 50px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 15px;
border-bottom: 1px solid #f0f0f0;
}
.back-btn {
font-size: 24px;
color: #333;
width: 40px;
}
.header-right {
width: 40px;
}
.title-text {
font-size: 16px;
font-weight: bold;
color: #333;
}
.menu-grid {
flex: 1;
display: flex;
flex-wrap: wrap;
padding: 20px 10px;
align-content: flex-start;
overflow-y: auto;
}
.menu-item {
width: 25%; /* 4列布局 */
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 25px;
}
.menu-icon {
width: 56px;
height: 56px;
border-radius: 16px; /* 大圆角 */
display: flex;
align-items: center;
justify-content: center;
font-size: 28px;
margin-bottom: 8px;
color: #fff;
}
.menu-text {
font-size: 12px;
color: #666;
text-align: center;
}
.file-list {
flex: 1;
padding: 0 15px;
}
.loading-tips, .empty-tips {
text-align: center;
padding: 20px;
color: #999;
font-size: 14px;
}
.file-item {
display: flex;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid #f5f5f5;
}
.file-item:active {
background-color: #f9f9f9;
}
.item-icon {
margin-right: 15px;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
background: #f0f0f0;
border-radius: 8px;
color: #999;
}
.item-info {
flex: 1;
display: flex;
flex-direction: column;
}
.item-name {
font-size: 16px;
color: #333;
margin-bottom: 4px;
}
.item-detail {
font-size: 12px;
color: #999;
}
.picker-footer {
height: 60px;
display: flex;
align-items: center;
justify-content: center;
border-top: 8px solid #f8f8f8; /* 分隔条效果 */
background: #fff;
}
.cancel-text {
font-size: 16px;
color: #333;
width: 100%;
text-align: center;
line-height: 50px;
}
</style>

View File

@@ -0,0 +1,532 @@
<template>
<view class="x-native-uploader">
<view class="upload-trigger" @click="handleSelect">
<slot>
<view class="default-btn">
<text class="plus">+</text>
<text class="text">选择文件并上传</text>
</view>
</slot>
</view>
<!-- 进度条展示 -->
<view v-if="files.length > 0" class="file-list">
<view v-for="(file, index) in files" :key="index" class="file-item">
<view class="file-info">
<text class="file-name">{{ file.name }}</text>
<view class="file-actions">
<text class="file-status">{{ file.statusText }}</text>
<text
class="delete-btn"
hover-class="delete-btn--hover"
hover-stay-time="80"
@click.stop="removeFile(index)"
>删除</text>
</view>
</view>
<view class="progress-bar">
<view class="progress-inner" :style="{ width: file.progress + '%' }"></view>
</view>
</view>
</view>
<!-- 文件选择器弹窗 -->
<x-file-picker ref="filePicker" :multiple="multiple" :limit="limit" @select="onFilePicked"></x-file-picker>
</view>
</template>
<script>
import xFilePicker from '../x-file-picker/x-file-picker.vue';
export default {
name: 'x-native-uploader',
components: {
xFilePicker
},
props: {
url: {
type: String,
required: true,
default: ''
},
// 上传参数
formData: {
type: Object,
default: () => ({})
},
// 请求头
header: {
type: Object,
default: () => ({})
},
// 文件字段名
name: {
type: String,
default: 'file'
},
// 是否自动上传
autoUpload: {
type: Boolean,
default: true
},
// 文件选择类型: image, video, all
fileType: {
type: String,
default: 'image'
},
// 是否多选
multiple: {
type: Boolean,
default: false
},
// 最大选择数量
limit: {
type: Number,
default: 9
}
},
data() {
return {
files: []
}
},
methods: {
handleSelect() {
// #ifdef APP-PLUS
this.selectFileNative();
// #endif
// #ifndef APP-PLUS
this.selectFileWeb();
// #endif
},
// Web/小程序端兼容
selectFileWeb() {
uni.chooseImage({
count: 1,
success: (res) => {
const tempFilePath = res.tempFilePaths[0];
this.processFile(tempFilePath);
}
});
},
// App端 Native 逻辑
selectFileNative() {
if (this.fileType === 'all') {
// 使用自定义的 Native.js 文件选择器 (x-file-picker)
// 替代不稳定的 uni.chooseFile
this.$refs.filePicker.open();
} else if (this.fileType === 'video') {
uni.chooseVideo({
count: 1,
success: (res) => {
const tempFilePath = res.tempFilePath;
// 尝试获取文件名,如果没有则从路径截取
let fileName = 'video.mp4';
if (res.tempFile && res.tempFile.name) {
fileName = res.tempFile.name;
} else {
fileName = tempFilePath.substring(tempFilePath.lastIndexOf('/') + 1);
}
this.processFile(tempFilePath, fileName);
}
});
} else {
// 默认图片
uni.chooseImage({
count: 1,
success: (res) => {
const tempFilePath = res.tempFilePaths[0];
// 从路径提取文件名
let fileName = 'image.jpg';
if (res.tempFiles && res.tempFiles[0] && res.tempFiles[0].name) {
fileName = res.tempFiles[0].name;
} else {
fileName = tempFilePath.substring(tempFilePath.lastIndexOf('/') + 1);
}
this.processFile(tempFilePath, fileName);
}
});
}
},
// 自定义文件选择器回调
onFilePicked(e) {
console.log('onFilePicked event:', e);
// e 可以是单个对象 {path, name} 或数组 [{path, name}, ...]
if (Array.isArray(e)) {
console.log('Processing array of files:', e.length);
e.forEach(item => {
this.processFile(item.path, item.name);
});
} else {
console.log('Processing single file');
this.processFile(e.path, e.name);
}
},
// 解析content:// URI为真实文件路径
resolveContentUri(path) {
// 非content URI直接返回
if (!path.startsWith('content://')) {
return Promise.resolve(path);
}
return new Promise((resolve) => {
// 1. 最优先处理用户遇到的raw:格式URI
// 匹配: content://.../document/raw%3A%2Fstorage%2Femulated%2F0%2F...
const rawMatch = path.match(/document\/raw%3A(.+)/);
if (rawMatch) {
try {
// 解码并恢复路径分隔符
const decodedPath = decodeURIComponent(rawMatch[1]);
resolve(decodedPath);
return;
} catch (e) {
console.warn('解码raw URI失败:', e);
}
}
// 2. 尝试使用plus.io解析
try {
plus.io.resolveLocalFileSystemURL(path, (entry) => {
resolve(entry.fullPath);
}, () => {
// 解析失败时返回原始路径
resolve(path);
});
} catch (e) {
// 任何异常都返回原始路径
resolve(path);
}
});
},
// 获取MediaStore中的文件路径
getMediaStorePath(contentUri, mainActivity) {
try {
const resolver = mainActivity.getContentResolver();
const cursor = resolver.query(plus.android.invoke('android.net.Uri', 'parse', contentUri),
['_data'], null, null, null);
if (cursor && cursor.moveToFirst()) {
const path = cursor.getString(0);
cursor.close();
return path;
}
} catch (e) {
console.error('获取MediaStore路径失败:', e);
}
return null;
},
processFile(path, name = 'unknown') {
this.resolveContentUri(path).then((realPath) => {
const fileObj = {
path: realPath,
name: name,
progress: 0,
status: 'pending', // pending, uploading, success, error
statusText: '等待上传'
};
this.files.push(fileObj);
if (this.autoUpload) {
// #ifdef APP-PLUS
this.uploadByNative(fileObj);
// #endif
// #ifndef APP-PLUS
this.uploadByUni(fileObj);
// #endif
}
}).catch((error) => {
// 如果解析失败仍然创建fileObj但是状态为error
const fileObj = {
path: path,
name: name,
progress: 0,
status: 'error',
statusText: '无法解析文件路径: ' + error.message
};
this.files.push(fileObj);
this.$emit('fail', { file: fileObj, error: error.message });
});
},
/**
* 使用 uni.uploadFile 进行上传
* 兼容 H5 和 小程序
*/
uploadByUni(fileObj) {
if (!this.url) {
uni.showToast({ title: '请配置上传URL', icon: 'none' });
return;
}
this.resolveContentUri(fileObj.path).then((realPath) => {
fileObj.status = 'uploading';
fileObj.statusText = '上传中...';
const uploadTask = uni.uploadFile({
url: this.url,
filePath: realPath,
name: this.name,
header: this.header,
formData: this.formData,
success: (uploadFileRes) => {
if (uploadFileRes.statusCode === 200) {
fileObj.progress = 100;
fileObj.status = 'success';
fileObj.statusText = '上传成功';
this.$emit('success', {
file: fileObj,
response: uploadFileRes.data
});
} else {
fileObj.status = 'error';
fileObj.statusText = '上传失败';
this.$emit('fail', {
file: fileObj,
error: uploadFileRes.statusCode
});
}
},
fail: (err) => {
fileObj.status = 'error';
fileObj.statusText = '上传失败';
this.$emit('fail', {
file: fileObj,
error: err
});
}
});
fileObj._task = uploadTask;
uploadTask.onProgressUpdate((res) => {
fileObj.progress = res.progress;
this.$emit('progress', {
file: fileObj,
progress: res.progress
});
});
}).catch((error) => {
fileObj.status = 'error';
fileObj.statusText = '无法解析文件路径: ' + error.message;
console.error('UploadByUni error:', error);
this.$emit('fail', { file: fileObj, error: error.message });
});
},
/**
* 使用 HTML5+ Native API 进行上传
* 这是 App 端推荐的“原生”上传方式
*/
uploadByNative(fileObj) {
if (!this.url) {
uni.showToast({ title: '请配置上传URL', icon: 'none' });
return;
}
this.resolveContentUri(fileObj.path).then((realPath) => {
fileObj.status = 'uploading';
fileObj.statusText = '上传中...';
// 创建上传任务
// 文档: https://www.html5plus.org/doc/zh_cn/uploader.html
const task = plus.uploader.createUpload(
this.url,
{
method: 'POST',
priority: 100
},
(upload, status) => {
// 上传完成回调
if (status === 200) {
fileObj.progress = 100;
fileObj.status = 'success';
fileObj.statusText = '上传成功';
this.$emit('success', {
file: fileObj,
response: upload.responseText
});
console.log('Upload success: ' + upload.responseText);
} else {
fileObj.status = 'error';
fileObj.statusText = '上传失败';
this.$emit('fail', {
file: fileObj,
error: status
});
console.log('Upload failed: ' + status);
}
}
);
fileObj._task = task;
// 添加上传文件
// addFile(path, options)
const added = task.addFile(realPath, { key: this.name });
if (!added) {
fileObj.status = 'error';
fileObj.statusText = '文件添加失败';
console.error('Task addFile failed');
this.$emit('fail', { file: fileObj, error: 'Failed to add file' });
return;
}
// 添加 header
if (this.header) {
for (const key in this.header) {
task.setRequestHeader(key, this.header[key]);
}
}
// 添加 formData
if (this.formData) {
for (const key in this.formData) {
task.addData(key, String(this.formData[key]));
}
}
// 监听进度
task.addEventListener('statechanged', (upload, status) => {
// upload.state: 3 (Connected/Uploading), 4 (Completed)
if (upload.state === 3) { // 上传中
const percent = Math.floor((upload.uploadedSize / upload.totalSize) * 100);
fileObj.progress = percent;
this.$emit('progress', {
file: fileObj,
progress: percent
});
}
});
// 开始上传
task.start();
}).catch((error) => {
fileObj.status = 'error';
fileObj.statusText = '无法解析文件路径: ' + error.message;
console.error('UploadByNative error:', error);
this.$emit('fail', { file: fileObj, error: error.message });
});
},
removeFile(index) {
const fileObj = this.files[index];
if (!fileObj) return;
const task = fileObj._task;
if (fileObj.status === 'uploading' && task) {
try {
if (typeof task.abort === 'function') {
task.abort();
}
} catch (e) {}
}
this.files.splice(index, 1);
this.$emit('remove', {
file: fileObj,
index
});
}
}
}
</script>
<style scoped>
.x-native-uploader {
width: 100%;
}
.upload-trigger {
width: 100%;
}
.default-btn {
width: 100%;
height: 100px;
border: 1px dashed #ccc;
border-radius: 8px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #f9f9f9;
}
.plus {
font-size: 40px;
color: #999;
line-height: 1;
}
.text {
font-size: 14px;
color: #666;
margin-top: 10px;
}
.file-list {
margin-top: 15px;
}
.file-item {
margin-bottom: 10px;
padding: 10px;
background: #fff;
border-radius: 4px;
box-shadow: 0 1px 4px rgba(0,0,0,0.1);
}
.file-info {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 5px;
font-size: 14px;
}
.file-actions {
display: flex;
align-items: center;
flex-shrink: 0;
margin-left: 12px;
}
.file-status {
color: #8a8f98;
font-size: 12px;
}
.delete-btn {
margin-left: 8px;
height: 24px;
line-height: 24px;
padding: 0 10px;
border-radius: 999px;
color: #ff3b30;
font-size: 12px;
font-weight: 500;
background: rgba(255, 59, 48, 0.08);
border: 1px solid rgba(255, 59, 48, 0.25);
}
.delete-btn--hover {
background: rgba(255, 59, 48, 0.16);
border-color: rgba(255, 59, 48, 0.35);
}
.file-name {
color: #333;
flex: 1;
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.progress-bar {
height: 4px;
background: #eee;
border-radius: 2px;
overflow: hidden;
}
.progress-inner {
height: 100%;
background: #007aff;
transition: width 0.3s;
}
</style>