vue3 双容器自动扩展布局 根据 内容的多少 动态定义宽度

需求:

左右两个列表 挨着排列,当左边内容超出滚动条时,换列显示,右边的列表随之移动

效果图:

1.左边数据:10,右边数据:5

2.左边数据:30,右边数据:5 此时:左边数据分两列显示,右边跟着移动

完整代码:

TypeScript 复制代码
<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view" style="overflow: auto">
      <div class="container1">
        <div class="left" ref="leftRef">
          <div v-for="n in leftItems" :key="n" class="item">Left {{ n }}</div>
          <button @click="clickBtn('left')">+</button>
        </div>
        <div class="right" ref="rightRef">
          <div v-for="n in rightItems" :key="n" class="item">Right {{ n }}</div>
          <button @click="clickBtn('right')">+</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted} from 'vue'

const leftItems = ref(180)
const rightItems = ref(50)
const leftRef = ref()
const rightRef = ref()

const clickBtn = (type) => {
  if (type == 'left') {
    leftItems.value++
    getData(leftRef.value)
  } else if (type == 'right') {
    rightItems.value++
    getData(rightRef.value)
  }
}
const getData = (ref) => {
  if (!ref) return
  const items = ref.querySelectorAll('.item')
  if (!items.length) return
  const itemHeight = items[0].offsetHeight + 10
  const containerHeight = ref.offsetHeight
  const columns = Math.ceil((items.length + 1) * itemHeight / containerHeight)
  ref.style.width = `${columns * 200}px`
  ref.style['min-width'] = `${columns * 200}px`
}
onMounted(async () => {
  getData(leftRef.value)
  getData(rightRef.value)
});


const updateSize = () => {
  getData(leftRef.value)
  getData(rightRef.value)
}

onMounted(() => {
  window.addEventListener('resize', updateSize)
})

onUnmounted(() => {
  window.removeEventListener('resize', updateSize)
})
</script>

<style scoped>
.container1 {
  display: flex;
  height: 100%;
  overflow: auto;
}

.left, .right {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: flex-start;
  gap: 10px;
  padding: 10px;
}

.item {
  padding: 10px;
  background: #eee;
  width: 180px;
  min-width: 180px;
}

button {
  margin-top: 10px;
  width: 180px;
}
</style>
相关推荐
Junerver42 分钟前
Kotlin 2.1.0的新改进带来哪些改变
前端·kotlin
千百元1 小时前
jenkins打包问题jar问题
前端
喝拿铁写前端1 小时前
前端批量校验还能这么写?函数式校验器组合太香了!
前端·javascript·架构
巴巴_羊1 小时前
6-16阿里前端面试记录
前端·面试·职场和发展
我是若尘1 小时前
前端遇到接口批量异常导致 Toast 弹窗轰炸该如何处理?
前端
该用户已不存在2 小时前
8个Docker的最佳替代方案,重塑你的开发工作流
前端·后端·docker
然我2 小时前
面试官最爱的 “考试思维”:用闭包秒杀递归难题 🚀
前端·javascript·面试
明月与玄武2 小时前
HTML知识全解析:从入门到精通的前端指南(上)
前端·html
teeeeeeemo2 小时前
CSS place-items: center; 详解与用法
前端·css·笔记
未来之窗软件服务2 小时前
html读取身份证【成都鱼住未来身份证】:CyberWinApp-SAAS 本地化及未来之窗行业应用跨平台架构
前端·html·身份证读取