jiangping
2023-10-26 68c5ef7d9fea3f911e250fb5f8b300bc76099e49
minipro_standard/uni_modules/uview-ui/components/u-album/u-album.vue
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,259 @@
<template>
    <view class="u-album">
        <view
            class="u-album__row"
            ref="u-album__row"
            v-for="(arr, index) in showUrls"
            :forComputedUse="albumWidth"
            :key="index"
        >
            <view
                class="u-album__row__wrapper"
                v-for="(item, index1) in arr"
                :key="index1"
                :style="[imageStyle(index + 1, index1 + 1)]"
                @tap="previewFullImage ? onPreviewTap(getSrc(item)) : ''"
            >
                <image
                    :src="getSrc(item)"
                    :mode="
                        urls.length === 1
                            ? imageHeight > 0
                                ? singleMode
                                : 'widthFix'
                            : multipleMode
                    "
                    :style="[
                        {
                            width: imageWidth,
                            height: imageHeight
                        }
                    ]"
                ></image>
                <view
                    v-if="
                        showMore &&
                        urls.length > rowCount * showUrls.length &&
                        index === showUrls.length - 1 &&
                        index1 === showUrls[showUrls.length - 1].length - 1
                    "
                    class="u-album__row__wrapper__text"
                >
                    <u--text
                        :text="`+${urls.length - maxCount}`"
                        color="#fff"
                        :size="multipleSize * 0.3"
                        align="center"
                        customStyle="justify-content: center"
                    ></u--text>
                </view>
            </view>
        </view>
    </view>
</template>
<script>
import props from './props.js'
// #ifdef APP-NVUE
// ç”±äºŽweex为阿里的KPI业绩考核的产物,所以不支持百分比单位,这里需要通过dom查询组件的宽度
const dom = uni.requireNativePlugin('dom')
// #endif
/**
 * Album ç›¸å†Œ
 * @description æœ¬ç»„件提供一个类似相册的功能,让开发者开发起来更加得心应手。减少重复的模板代码
 * @tutorial https://www.uviewui.com/components/album.html
 *
 * @property {Array}           urls             å›¾ç‰‡åœ°å€åˆ—表 Array<String>|Array<Object>形式
 * @property {String}          keyName          æŒ‡å®šä»Žæ•°ç»„的对象元素中读取哪个属性作为图片地址
 * @property {String | Number} singleSize       å•图时,图片长边的长度  ï¼ˆé»˜è®¤ 180 ï¼‰
 * @property {String | Number} multipleSize     å¤šå›¾æ—¶ï¼Œå›¾ç‰‡è¾¹é•¿ ï¼ˆé»˜è®¤ 70 ï¼‰
 * @property {String | Number} space            å¤šå›¾æ—¶ï¼Œå›¾ç‰‡æ°´å¹³å’Œåž‚直之间的间隔 ï¼ˆé»˜è®¤ 6 ï¼‰
 * @property {String}          singleMode       å•图时,图片缩放裁剪的模式 ï¼ˆé»˜è®¤ 'scaleToFill' ï¼‰
 * @property {String}          multipleMode     å¤šå›¾æ—¶ï¼Œå›¾ç‰‡ç¼©æ”¾è£å‰ªçš„æ¨¡å¼ ï¼ˆé»˜è®¤ 'aspectFill' ï¼‰
 * @property {String | Number} maxCount         å–消按钮的提示文字 ï¼ˆé»˜è®¤ 9 ï¼‰
 * @property {Boolean}         previewFullImage æ˜¯å¦å¯ä»¥é¢„览图片 ï¼ˆé»˜è®¤ true ï¼‰
 * @property {String | Number} rowCount         æ¯è¡Œå±•示图片数量,如设置,singleSize和multipleSize将会无效   ï¼ˆé»˜è®¤ 3 ï¼‰
 * @property {Boolean}         showMore         è¶…出maxCount时是否显示查看更多的提示 ï¼ˆé»˜è®¤ true ï¼‰
 *
 * @event    {Function}        albumWidth       æŸäº›ç‰¹æ®Šçš„æƒ…况下,需要让文字与相册的宽度相等,这里事件的形式对外发送  ï¼ˆå›žè°ƒå‚æ•° width ï¼‰
 * @example <u-album :urls="urls2" @albumWidth="width => albumWidth = width" multipleSize="68" ></u-album>
 */
export default {
    name: 'u-album',
    mixins: [uni.$u.mpMixin, uni.$u.mixin, props],
    data() {
        return {
            // å•图的宽度
            singleWidth: 0,
            // å•图的高度
            singleHeight: 0,
            // å•图时,如果无法获取图片的尺寸信息,让图片宽度默认为容器的一定百分比
            singlePercent: 0.6
        }
    },
    watch: {
        urls: {
            immediate: true,
            handler(newVal) {
                if (newVal.length === 1) {
                    this.getImageRect()
                }
            }
        }
    },
    computed: {
        imageStyle() {
            return (index1, index2) => {
                const { space, rowCount, multipleSize, urls } = this,
                    { addUnit, addStyle } = uni.$u,
                    rowLen = this.showUrls.length,
                    allLen = this.urls.length
                const style = {
                    marginRight: addUnit(space),
                    marginBottom: addUnit(space)
                }
                // å¦‚果为最后一行,则每个图片都无需下边框
                if (index1 === rowLen) style.marginBottom = 0
                // æ¯è¡Œçš„æœ€å³è¾¹ä¸€å¼ å’Œæ€»é•¿åº¦çš„æœ€åŽä¸€å¼ æ— éœ€å³è¾¹æ¡†
                if (
                    index2 === rowCount ||
                    (index1 === rowLen &&
                        index2 === this.showUrls[index1 - 1].length)
                )
                    style.marginRight = 0
                return style
            }
        },
        // å°†æ•°ç»„划分为二维数组
        showUrls() {
            const arr = []
            this.urls.map((item, index) => {
                // é™åˆ¶æœ€å¤§å±•示数量
                if (index + 1 <= this.maxCount) {
                    // è®¡ç®—该元素为第几个素组内
                    const itemIndex = Math.floor(index / this.rowCount)
                    // åˆ¤æ–­å¯¹åº”的索引是否存在
                    if (!arr[itemIndex]) {
                        arr[itemIndex] = []
                    }
                    arr[itemIndex].push(item)
                }
            })
            return arr
        },
        imageWidth() {
            return uni.$u.addUnit(
                this.urls.length === 1 ? this.singleWidth : this.multipleSize
            )
        },
        imageHeight() {
            return uni.$u.addUnit(
                this.urls.length === 1 ? this.singleHeight : this.multipleSize
            )
        },
        // æ­¤å˜é‡æ— å®žé™…用途,仅仅是为了利用computed特性,让其在urls长度等变化时,重新计算图片的宽度
        // å› ä¸ºç”¨æˆ·åœ¨æŸäº›ç‰¹æ®Šçš„æƒ…况下,需要让文字与相册的宽度相等,所以这里事件的形式对外发送
        albumWidth() {
            let width = 0
            if (this.urls.length === 1) {
                width = this.singleWidth
            } else {
                width =
                    this.showUrls[0].length * this.multipleSize +
                    this.space * (this.showUrls[0].length - 1)
            }
            this.$emit('albumWidth', width)
            return width
        }
    },
    methods: {
        // é¢„览图片
        onPreviewTap(url) {
            const urls = this.urls.map((item) => {
                return this.getSrc(item)
            })
            uni.previewImage({
                current: url,
                urls
            })
        },
        // èŽ·å–å›¾ç‰‡çš„è·¯å¾„
        getSrc(item) {
            return uni.$u.test.object(item)
                ? (this.keyName && item[this.keyName]) || item.src
                : item
        },
        // å•图时,获取图片的尺寸
        // åœ¨å°ç¨‹åºä¸­ï¼Œéœ€è¦å°†ç½‘络图片的的域名添加到小程序的download域名才可能获取尺寸
        // åœ¨æ²¡æœ‰æ·»åŠ çš„æƒ…å†µä¸‹ï¼Œè®©å•å›¾å®½åº¦é»˜è®¤ä¸ºç›’å­çš„ä¸€å®šå®½åº¦(singlePercent)
        getImageRect() {
            const src = this.getSrc(this.urls[0])
            uni.getImageInfo({
                src,
                success: (res) => {
                    // åˆ¤æ–­å›¾ç‰‡æ¨ªå‘还是竖向展示方式
                    const isHorizotal = res.width >= res.height
                    this.singleWidth = isHorizotal
                        ? this.singleSize
                        : (res.width / res.height) * this.singleSize
                    this.singleHeight = !isHorizotal
                        ? this.singleSize
                        : (res.height / res.width) * this.singleWidth
                },
                fail: () => {
                    this.getComponentWidth()
                }
            })
        },
        // èŽ·å–ç»„ä»¶çš„å®½åº¦
        async getComponentWidth() {
            // å»¶æ—¶ä¸€å®šæ—¶é—´ï¼Œä»¥èŽ·å–dom尺寸
            await uni.$u.sleep(30)
            // #ifndef APP-NVUE
            this.$uGetRect('.u-album__row').then((size) => {
                this.singleWidth = size.width * this.singlePercent
            })
            // #endif
            // #ifdef APP-NVUE
            // è¿™é‡Œref="u-album__row"所在的标签为通过for循环出来,导致this.$refs['u-album__row']是一个数组
            const ref = this.$refs['u-album__row'][0]
            ref &&
                dom.getComponentRect(ref, (res) => {
                    this.singleWidth = res.size.width * this.singlePercent
                })
            // #endif
        }
    }
}
</script>
<style lang="scss" scoped>
@import '../../libs/css/components.scss';
.u-album {
    @include flex(column);
    &__row {
        @include flex(row);
        flex-wrap: wrap;
        &__wrapper {
            position: relative;
            &__text {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: rgba(0, 0, 0, 0.3);
                @include flex(row);
                justify-content: center;
                align-items: center;
            }
        }
    }
}
</style>