javascript
<template>
<div id="fb-content" :style="{ padding: '0 ' + boxPadding + 'px' }">
<div
v-for="(item, index) in props['boxList']"
:key="index"
:style="{ width: 100 / boxNum + '%' }"
>
<div style="display: flex; justify-content: center">
<slot name="box" :item="item"></slot>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { defineProps, onMounted, ref } from 'vue';
const props = defineProps({
boxWidth: {
type: Number,
default: 1,
},
gap: {
type: Number,
default: 1,
},
boxList: {
type: Object,
},
});
const boxNum = ref(0);
const boxPadding = ref(0);
onMounted(() => {
init();
window.addEventListener('resize', () => {
//监听页面变化
init();
});
});
function init() {
let dom = document.getElementById('fb-content');
let contentWidth = dom?.clientWidth || dom?.offsetWidth || 1;
boxNum.value = contentWidth
? parseInt((contentWidth - props['gap']) / (props.boxWidth + props['gap']))
: 1;
boxPadding.value = parseInt(
(contentWidth - (props['boxWidth'] + props['gap']) * boxNum.value) / 2,
);
}
</script>
<style lang="less">
#fb-content {
width: 100%;
display: flex;
flex-wrap: wrap;
align-items: center;
}
</style>
间距固定,左右padding自适应