SmartParks_uniapp/utils/mediaSelector.example.js

136 lines
2.8 KiB
JavaScript

/**
* 媒体选择器使用示例
*/
// 导入媒体选择器工具类
import MediaSelector, { MediaType } from './mediaSelector';
/**
* 选择图片示例
*/
export async function chooseImagesExample() {
try {
// 选择最多9张图片
const images = await MediaSelector.choose({
type: MediaType.IMAGE,
count: 9,
compressed: true,
crop: false
});
console.log('选择的图片:', images);
return images;
} catch (error) {
console.error('选择图片失败:', error);
uni.showToast({
title: '选择图片失败',
icon: 'none'
});
return [];
}
}
/**
* 选择视频示例
*/
export async function chooseVideosExample() {
try {
// 选择最多1个视频
const videos = await MediaSelector.choose({
type: MediaType.VIDEO,
count: 1,
compressed: true,
videoMaxDuration: 60 // 最长60秒
});
console.log('选择的视频:', videos);
return videos;
} catch (error) {
console.error('选择视频失败:', error);
uni.showToast({
title: '选择视频失败',
icon: 'none'
});
return [];
}
}
/**
* 选择图片或视频示例(用户可选择)
*/
export async function chooseBothExample() {
try {
// 让用户选择图片或视频
const media = await MediaSelector.choose({
type: MediaType.BOTH,
count: 5
});
console.log('选择的媒体:', media);
return media;
} catch (error) {
console.error('选择媒体失败:', error);
uni.showToast({
title: '选择媒体失败',
icon: 'none'
});
return [];
}
}
/**
* 预览媒体示例
* @param {Object} mediaItem 媒体项
*/
export function previewMediaExample(mediaItem) {
if (!mediaItem || !mediaItem.path) {
uni.showToast({
title: '无效的媒体文件',
icon: 'none'
});
return;
}
// 预览媒体(自动判断类型)
MediaSelector.preview(mediaItem.path, mediaItem.type);
}
/**
* 在页面中使用的完整示例
*/
export default {
data() {
return {
mediaList: [] // 存储选择的媒体列表
};
},
methods: {
// 选择图片
async chooseImages() {
const images = await chooseImagesExample();
this.mediaList = [...this.mediaList, ...images];
},
// 选择视频
async chooseVideos() {
const videos = await chooseVideosExample();
this.mediaList = [...this.mediaList, ...videos];
},
// 选择图片或视频
async chooseBoth() {
const media = await chooseBothExample();
this.mediaList = [...this.mediaList, ...media];
},
// 预览媒体
previewMedia(item) {
previewMediaExample(item);
},
// 删除媒体
deleteMedia(index) {
this.mediaList.splice(index, 1);
}
}
};