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>
相关推荐
卷福同学1 小时前
AI编程出海第二步:验证关键词能否做站
前端·人工智能·后端
开普勒chr1 小时前
css样式diaplay:"contents"的妙用
css
赵庆明老师1 小时前
Vben精讲:21-详解web-antd:tsconfig.json
前端·json·vim
wc881 小时前
微软EDGE浏览器功能学习
前端·学习·edge
破z晓1 小时前
javascript 导出excel表
开发语言·javascript·excel
Csvn2 小时前
🎯 原生 `<dialog>` 元素:终于可以扔掉一半的自定义弹窗组件了?
前端
Csvn2 小时前
🎨 CSS @layer:用「层叠优先级」终结样式打架的世纪难题
前端
小罗水3 小时前
第17章 后台管理端与演示支持
javascript·vue.js·ecmascript
濮水大叔3 小时前
不必把 Vue3 写成“麻花”:从状态碎片到对象协作,重新理解 Zova 的前端心智模型
前端·typescript·vue3·ioc·tsx·zova
Vuji3 小时前
MCP: 一条 tool 调用链路的旅程
前端·人工智能