微信小程序结合vant weapp ui实现多图上传组件

微信小程序多图上传

最近在写小程序的商品上传,为方便需要使用多张图片的上传的功能。因为小程序不支持数组的多张图片同时上传,然后根据自己的需求创建了一个组件希望能够帮到大家

效果图

在这里插入图片描述

  1. 创建一个图片上传的promise
	uploadFilePromise(filePath, Authorization) {
            return new Promise(function(resolve, reject) {
                wx.uploadFile({
                    url: `${DOMAIN}File/Image/upload`,
                    filePath,
                    name: 'file',
                    header: {
                        Authorization,
                    },
                    success: res => {
                        // 触发图片上传事件
                        let data = JSON.parse(res.data);
                        if (data.code != SUCCESS_CODE) {   //SUCCESS_CODE为本项目请求成功的判断无需在意
                            wx.showToast({
                                title: data.message || '上传失败',
                                icon: 'none'
                            })
                        } else {
                            resolve(res)
                        }
                    },
                    fail: res => {
                        reject(res)
                    }
                });
            })
        },
  1. 创建一个promise.all (多个图片上传成功后再改变dom)
	chooseImage(){
			wx.chooseImage({
                count,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success(res) {
                    const tempFilePaths = res.tempFilePaths;  //拿到选择的图片地址
                    that.triggerEvent('disableBtn', {}, {});  //上传过程中禁用父组件中的保存按钮,防止图片未上传成功
                    let promiseList = tempFilePaths.map(temp => that.uploadFilePromise(temp, Authorization));  //获取promise 队列数组
                    Promise.all(promiseList).then((result) => {
                        let uploadImgList = result.map(item => ({ file_key: JSON.parse(item.data).data.key, url: JSON.parse(item.data).data.url })).reverse();
                        imgList.unshift(...uploadImgList);  //将新上传的图片从头部插入原图片数组中
                        that.triggerEvent('Upload', { imgList, key })  //上传成功将新的图片数组给到组件
                    })
                }
            })
 	}
  1. 完整js 文件
 	import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import {
    DOMAIN,
    TOKEN_KEY,
    SUCCESS_CODE
} from "../../../../configs";
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        imgList: {  //图片列表
            type: [Array],
            value: [],
        },
        max: {  //最大可以上传数
            type: [Number],
            value: 10
        },
        key: { //图片列表key
            type: [String],
            value: ''
        }
    },

    /**
     * 组件的初始数据
     */
    data: {

    },
    
    methods: {
        upload(e) {
            const {key,max} = e.target.dataset;
            let imgList = this.data.imgList,
                listLen=imgList.length,
                count = parseInt(max - listLen) > 9 ? 9 : parseInt(max - listLen),
                that = this;
            var Authorization = wx.getStorageSync(TOKEN_KEY);
            if (listLen >= max) {
                wx.showToast({
                    title: `最多上传${max}张图片`,
                    icon: 'none',
                    duration: 2000
                });
                return false;
            }
            wx.chooseImage({
                count,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success(res) {
                    const tempFilePaths = res.tempFilePaths;
                    that.triggerEvent('disableBtn', {}, {});
                    let promiseList = tempFilePaths.map(temp => that.uploadFilePromise(temp, Authorization));
                    Promise.all(promiseList).then((result) => {
                        let uploadImgList = result.map(item => ({ file_key: JSON.parse(item.data).data.key, url: JSON.parse(item.data).data.url })).reverse();
                        imgList.unshift(...uploadImgList);
                        that.triggerEvent('Upload', { imgList, key })
                    })
                }
            })
        },
        uploadFilePromise(filePath, Authorization) {
            return new Promise(function(resolve, reject) {
                wx.uploadFile({
                    url: `${DOMAIN}File/Image/upload`,
                    filePath,
                    name: 'file',
                    header: {
                        Authorization,
                    },
                    success: res => {
                        // 触发图片上传事件
                        let data = JSON.parse(res.data);
                        if (data.code != SUCCESS_CODE) {
                            wx.showToast({
                                title: data.message || '上传失败',
                                icon: 'none'
                            })
                        } else {
                            resolve(res)
                        }
                    },
                    fail: res => {
                        reject(res)
                    }
                });
            })
        },
        delete(e) {
            const { key, index } = e.target.dataset;
            Dialog.confirm({
                selector: '#create-dialog',
                title: '提示',
                message: '确认删除该图吗?'
            }).then(() => {
                this.triggerEvent('Delete', {key,index})
            }).catch(() => {
                // on cancel
            })
        },
    }
})
  1. 创建一个wxml
<view class="product-img-list">
	<view class="img-box" wx:for="{{imgList}}" wx:key="index">
		<van-image src="{{item.url}}" mode="widthFix"   lazy-load custom-class="product-img"></van-image>
		<view bindtap="delete" data-index="{{index}}" data-key="{{key}}">删除</view>
	</view>
	<image src="http://image.end.wiki/aimaimaiCtianjia@2x.png?imageslim" data-key="{{key}}" data-max="{{max}}" class="add-image-icon" bindtap="upload" mode="aspectFit|aspectFill|widthFix" lazy-load="false" binderror="" bindload=""></image>
</view>
  1. 写上样式wxss
.product-img-list {
    display: flex;
    flex-wrap: wrap;
}

.product-img-list .img-box {
    width: 100rpx;
    margin-right: 24rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #909090;
    font-size: 28rpx;
    margin-top: 32rpx;
}

.img-box .product-img{
    width: 100rpx;
    height: 100rpx;
    margin-bottom: 24rpx;
}

.add-image-icon {
    width: 100rpx;
    height: 100rpx;
    margin-top: 32rpx;
}
  1. 父组件的调用–wxml
<banner-uploader max="10" imgList="{{form.bannerList}}" key="bannerList" bindUpload="uploadProImg" bindDelete="deleteProImg" binddisableBtn="disableBtn"></banner-uploader>

7.父组件的调用 --js

 //上传图片
    uploadProImg(e) {
        let form = this.data.form,
            key = e.detail.key,
            imgList = e.detail.imgList;
        form[key] = imgList;
        this.setData({ form, btnDisabled: false })
    },
    //上传按钮禁用
    disableBtn(e) {
        this.setData({ btnDisabled: true })
    },
    //删除图片
    deleteProImg(e) {
        let form = this.data.form,
            key = e.detail.key,
            index = e.detail.index,
            keyList = form[key];
        keyList.splice(index, 1);
        form[key] = keyList;
        this.setData({ form })
    },
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
微信小程序vant weapp提供了TreeSelect组件实现三级分类选择。要实现三级分类选择,我们需要先获取分类数据,并将其转换为树状结构。 首先,在小程序页面的json文件中引入vant组件库,并设置所需的TreeSelect组件。 ```json { "usingComponents": { "van-tree-select": "/path/to/vant/weapp/dist/tree-select/index" } } ``` 然后,在小程序页面的wxml文件中添加TreeSelect组件,并绑定所需的属性和事件。 ```html <van-tree-select items="{{ treeData }}" main-active-index="{{ mainActiveIndex }}" activeId="{{ activeId }}" bind:click-nav="handleClickNav" bind:click-item="handleClickItem" /> ``` 在小程序页面的js文件中,定义相关数据和方法。 ```javascript Page({ data: { treeData: [], // 分类数据 mainActiveIndex: 0, // 主选项卡索引 activeId: '', // 选中的分类id }, onLoad() { // 获取分类数据,并将其转换为树状结构 const data = this.getCategoryData(); const treeData = this.convertToTree(data); this.setData({ treeData: treeData }); }, getCategoryData() { // 从接口或本地获取分类数据 // 返回分类数据数组 }, convertToTree(data) { // 将分类数据转换为树状结构 // 返回树状结构的数据 }, handleClickNav(event) { // 切换主选项卡时的回调函数 this.setData({ mainActiveIndex: event.detail.index }); }, handleClickItem(event) { // 选择子分类时的回调函数 this.setData({ activeId: event.detail.id }); } }); ``` 通过以上步骤,我们就可以使用微信小程序vant weapp实现三级treeselect分类选择功能了。需要注意的是,具体的分类数据获取和转换还需要根据实际情况进行处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值