一、环境准备
在开始之前,请确保你的项目中已经安装了以下依赖:
- Vue.js:用于构建前端界面
- Vue Router:用于页面路由管理
- Vuex:用于状态管理(可选)
- Vant UI:提供丰富的移动端组件(可选)
npm install vue vue-router vuex vant
二、图片选择
<template>
<van-uploader :after-read="handleAfterRead" />
</template>
<script>
export default {
methods: {
handleAfterRead(file) {
// 图片选择成功后的处理逻辑
// 这里可以调用图片预览、上传等操作
}
}
}
</script>
三、图片预览
<template>
<van-preview
:images="previewImages"
@change="handlePreviewChange"
/>
</template>
<script>
export default {
data() {
return {
previewImages: []
};
},
methods: {
handleAfterRead(file) {
this.previewImages.push(file.url);
},
handlePreviewChange(index) {
// 图片预览切换时的处理逻辑
}
}
}
</script>
四、图片上传
<template>
<van-button type="primary" @click="handleUpload">上传图片</van-button>
</template>
<script>
import axios from 'axios';
export default {
methods: {
handleAfterRead(file) {
this.previewImages.push(file.url);
},
handleUpload() {
const formData = new FormData();
formData.append('file', this.previewImages[0]);
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
// 上传成功后的处理逻辑
}).catch(error => {
// 上传失败的处理逻辑
});
}
}
}
</script>
五、图片保存到本地设备
<template>
<van-button type="primary" @click="handleDownload">保存图片</van-button>
</template>
<script>
export default {
methods: {
handleAfterRead(file) {
this.previewImages.push(file.url);
},
handleDownload() {
const link = document.createElement('a');
link.href = this.previewImages[0];
link.download = 'image.png'; // 设置下载文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
</script>