【uniapp】图片九宫格、自定义一行显示多个、图片集合、左右平分

  • Post author:
  • Post category:uniapp


看清楚代码备注

【dcloud 下载

图片九宫格

在这里插入图片描述



1、index.vue

<template>
	<view class="content"><telPic :imageArr="arr" :lineNum="lineNum" :spacingNumber="spacingNumber"></telPic></view>
</template>
<script>
import telPic from '../../components/tel-pic.vue';
export default {
	components: {
		telPic
	},
	data() {
		return {
			arr: [],
			lineNum: 3, //行数 备注:修改此数据时 一定要修改tel-pic底部css伪类样式  修改此字段必须修改css样式第70行代码
			spacingNumber: 5 //行间距单位px
		};
	},
	onLoad() {
		for (var i = 0; i < 20; i++) {
			var urls = 'https://picsum.photos/450/450?random=' + i;
			this.arr.push(urls);
		}
	},
	methods: {}
};
</script>

<style></style>



2、tel-pic.vue

<template>
	<view class="pic-container" :style="{
	paddingLeft:spacingNumber+'px',
	paddingRight:spacingNumber+'px'
	}">
		<view class="tel-pic-show">
			<view class="pic-box">
				<block v-for="(item, i) in imageArr" :key="i">
					<view class="img" @click="prevsImages(imageArr, i)" :style="{ backgroundImage: 'url(' + item + ')', 
						width: imgW + 'px',
						 height: imgH + 'px',
						 marginBottom:spacingNumber+'px',
						 marginRight:spacingNumber+'px' }">
					</view>
				</block>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		props:['imageArr','lineNum','spacingNumber'],
		data() {
			return {
				imgW: '', //图片宽
				imgH: '', //图片高
				screenWidth: 0, //屏幕宽度
			};
		},
		mounted() {
			const self = this;
			uni.createSelectorQuery().in(this).select('.tel-pic-show').boundingClientRect(data => {
				self.screenWidth = data.width;
				self.imgW = (self.screenWidth - (self.lineNum - 1) * self.spacingNumber) / self.lineNum;
				self.imgH = self.imgW;
			}).exec();
		},
		methods: {
			prevsImages(arr, i) {
				uni.previewImage({
					urls: arr,
					current: i
				});
			}
		}
	};
</script>
<style lang="scss">
	.pic-container {
		width: 100%;
		box-sizing: border-box;
	}
	.tel-pic-show {
		width: 100%;
		.pic-box {
			width: 100%;
			display: flex;
			justify-content: flex-start;
			align-items: center;
			flex-wrap: wrap;
			.img {
				overflow: hidden;
				background-position: center center;
				background-size: cover;
				background-repeat: no-repeat;
				display: inline-block;
				border-radius: 16rpx;
			}
			// 3来源于 :行数 字段:lineNum
			.img:nth-child(3n + 3) {
				margin-right: 0px !important;
			}
		}
	}
</style>



版权声明:本文为weixin_42216995原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。