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>
相关推荐
xjt_090113 分钟前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js
我是伪码农24 分钟前
Vue 2.3
前端·javascript·vue.js
夜郎king1 小时前
HTML5 SVG 实现日出日落动画与实时天气可视化
前端·html5·svg 日出日落
辰风沐阳1 小时前
JavaScript 的宏任务和微任务
javascript
跳动的梦想家h1 小时前
环境配置 + AI 提效双管齐下
java·vue.js·spring
夏幻灵2 小时前
HTML5里最常用的十大标签
前端·html·html5
冰暮流星2 小时前
javascript之二重循环练习
开发语言·javascript·数据库
Mr Xu_2 小时前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js
未来龙皇小蓝2 小时前
RBAC前端架构-01:项目初始化
前端·架构
程序员agions2 小时前
2026年,微前端终于“死“了
前端·状态模式