图片/背景图的自适应 2.0版本(vue3)

创建文件 RemImg.vue

<template>
	<!-- 图片类型 -->
	<img 
		v-if="props.mode=='img'" 
		class="rem-img" ref="img" alt="#" 
		:src="props.src" :style="{width,height}" 
	/>
	<!-- 背景图类型 -->
	<div 
		v-else-if="props.mode=='bg'"	
		:style="{width,height,background:`url(${props.src}) center/100% 100% no-repeat`}"
	>
		<slot></slot>
	</div>
</template>

<script setup>
	import { onMounted, ref, watch } from 'vue'; //组合API

	const props = defineProps({ // 父组件传来的值
		src: {  // 图片路径
			type: String
		},
		mode: { // 模式 是 图片 还是 背景
			type: String,
			default: 'img'
		},
		remMode: { // 自适应模式 是 px 还是 rem 
			type:String,
			default:'rem'
		},
		isFullWidth:{ // 是否原尺寸宽度
			type: Boolean,
			default: false
		},
		isFullHeight:{ // 是否原尺寸高度
			type: Boolean,
			default: false
		}
	});

	const width = ref(0);
	const height = ref(0);

	watch(()=>props.src,(src)=>{ //监听 图片 的路径
		console.log(src)
	},{
		immediate:true,
		deep:true
	})

	onMounted(()=>{ // 生命周期
		const img = new Image()
		img.onload = () =>{ // 修改 图片大小 单位 px or rem

			switch(props.remMode){
				case 'px':
					width.value = img.naturalWidth + 'px'
					height.value = img.naturalHeight + 'px'
					break
				case 'rem':
					if(props.isFullWidth){
						width.value = img.naturalWidth + 'px'
						height.value = img.naturalHeight / 100 + 'rem'
					}else if(props.isFullHeight){
						width.value = img.naturalWidth  / 100 + 'rem'
				 		height.value = img.naturalHeight + 'px'
					}else{
						width.value = img.naturalWidth / 100 + 'rem'
						height.value = img.naturalHeight / 100 + 'rem'
					}
					break
			}
		} 

		watch(()=>props.src,(src)=>{ // 重置图片
			img.src = src
		},{
			immediate:true,
			deep:true
		})
		
	})
</script>

使用:

1. import RemImg from '_c/RemImg.vue';
2. <RemImg 
	:src="require('../assets/images/frame/rotate-bg.png')" 
	mode="bg" 
	remMode="rem"
   >
    <div>插槽自适应背景图片</div>
   </RemImg>

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