接下来我将分享一个关于 Vue+Vant 图片上传加显示的完整攻略。我们需要安装 Vant 和 vue-cropper 插件,然后进行如下步骤:
接下来我将分享一个关于 Vue+Vant 图片上传加显示的完整攻略。我们需要安装 Vant 和 vue-cropper 插件,然后进行如下步骤:
- 在 HTML 中创建一个上传文件的 input 元素
<input type="file" accept="image/*" @change="handleFileChange($event)">
- 在 Vue 中绑定 handleFileChange 函数,该函数用来读取用户选择的图片并将其转换为可预览的 URL,并用 vant 的 ImagePreview 组件显示图片预览。
handleFileChange(event) {
const files = event.target.files;
if (!files.length) {
return;
}
// 使用 FileReader 读取文件并将其转为 Data URL
const fileReader = new FileReader();
fileReader.readAsDataURL(files[0]);
fileReader.onload = () => {
// 将 Data URL 赋值给 imageDataUrl
this.imageDataUrl = fileReader.result;
// 使用 ImagePreview 组件预览图片
ImagePreview(this.imageDataUrl);
}
}
- 在 HTML 模板中使用 vant 的 ImagePreview 组件来预览上传的图片。
<van-image-preview :images="imageDataUrl" v-if="imageDataUrl" @close="imageDataUrl = ''"></van-image-preview>
- 结合 vue-cropper 插件,可以实现剪裁并上传用户选择的图片。在 HTML 中添加一个按钮,用来触发 ImageCropModal 组件。
<van-button type="primary" @click="showCropModal">上传图片</van-button>
- 在 Vue 中绑定 showCropModal 函数,该函数用来显示 ImageCropModal 组件。
showCropModal() {
// 显示 ImageCropModal 组件
this.showImageCropModal = true;
}
- 在 ImageCropModal 组件中,引入 vue-cropper 插件,通过 v-bind 传递 imageDataUrl、width、height 等参数,并将用户剪裁过的图片重新赋值给 imageDataUrl,最后将 imageDataUrl 赋值给 showImageCropModal 参数,隐藏 ImageCropModal 组件并在 vant 的 ImagePreview 组件中预览图片。
<template>
<van-popup v-model="show" position="bottom">
<div class="crop-modal">
<vue-cropper
ref="cropper"
v-bind:src="imageDataUrl"
:width="width"
:height="height"
:output-type="outputType"
:output-quality="outputQuality"
></vue-cropper>
<div class="crop-modal-footer">
<van-button size="large" @click="cancelCrop">取消</van-button>
<van-button size="large" type="primary" @click="cropImage">
确定
</van-button>
</div>
</div>
</van-popup>
</template>
<script>
import { Popup, Button } from 'vant';
import VueCropper from 'vue-cropper';
export default {
components: {
Popup,
Button,
VueCropper,
},
props: {
imageDataUrl: {
type: String,
default: '',
},
width: {
type: Number,
default: 300,
},
height: {
type: Number,
default: 300,
},
outputType: {
type: String,
default: 'jpeg',
},
outputQuality: {
type: Number,
default: 0.8,
},
},
data() {
return {
show: true,
};
},
methods: {
cancelCrop() {
this.show = false;
},
cropImage() {
this.$refs.cropper
.getCroppedCanvas()
.toBlob((blob) => {
const fileReader = new FileReader();
fileReader.readAsDataURL(blob);
fileReader.onload = () => {
this.imageDataUrl = fileReader.result;
this.show = false;
ImagePreview(this.imageDataUrl);
};
}, this.outputType, this.outputQuality);
},
},
};
</script>
以上就是 Vue+Vant 图片上传加显示的完整攻略,实际使用应根据具体业务需求进行调整。
织梦狗教程
本文标题为:Vue+Vant 图片上传加显示的案例


基础教程推荐
猜你喜欢
- js获取浏览器的各种属性 2024-01-06
- span 右浮动折行 解决ie6/7中span右浮动折行问题 2023-12-13
- vue项目接收二进制流展示表格 2023-10-08
- JavaScript动态生成二维码图片 2023-12-21
- 详解CSS3+JS完美实现放大镜模式 2023-12-29
- css 半透明 让IE6支持png图片半透明解决方法 2023-12-28
- 关于ES6中的箭头函数超详细梳理 2022-08-30
- CSS简单实现网页悬浮效果(对联广告) 2023-12-29
- cmd命令如何启动vue项目 2023-10-08
- Vue自学之路1-vue概述 2023-10-08