https://blog.csdn.net/m0_46690660/article/details/126429117 你好请问这篇文章父容器高度要如何做自适应,可以加一下你的微信请教一下吗?
4条回答 默认 最新
笑面虎 2023-04-16 14:50关注以下内容引用CHATGPT、有用望采纳:
可以通过监听图片加载完成的事件,然后重新计算父容器的高度来实现自适应。具体实现思路如下:
在父容器中,设置一个 data 属性 imgList 存储所有图片的地址。
在 mounted 钩子函数中,循环遍历 imgList 数组,将图片地址作为 key,将图片加载状态设置为 false,存储在一个对象中。
在每个图片的 onload 事件中,将该图片的加载状态设置为 true。
监听对象的变化,当所有图片都加载完成时,重新计算父容器的高度。
代码示例:
<template> <div ref="parent" class="parent"> <div class="item" v-for="(item, index) in imgList" :key="index"> <img :src="item" @load="handleImgLoad(item)"> </div> </div> </template> <script> export default { data() { return { imgList: [ 'https://example.com/image1.jpg', 'https://example.com/image2.jpg', 'https://example.com/image3.jpg', // ... ], imgLoaded: {} } }, mounted() { this.imgList.forEach(item => { this.$set(this.imgLoaded, item, false) }) }, methods: { handleImgLoad(key) { this.$set(this.imgLoaded, key, true) if (Object.values(this.imgLoaded).every(item => item === true)) { this.$nextTick(() => { this.$refs.parent.style.height = 'auto' }) } } } } </script> <style scoped> .parent { width: 100%; display: flex; flex-wrap: wrap; } .item { width: 33.33%; padding: 10px; box-sizing: border-box; } .item img { width: 100%; } </style>解决 无用评论 打赏 举报