Vue木桶布局插件

发布时间:2019-05-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Vue木桶布局插件脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

    公司最近在重构,使用的是Vue框架。涉及到一个品牌的布局,因为品牌的字符长度不一致,所以导致每一个的品牌标签长短不一。多行布局下就会导致每行的品牌布局参差不齐,严重影响美观。于是就有了本篇的木桶布局插件。

木桶布局的实现是这样分步骤的:
  1. 首先对要填放的内容进行排序,筛选出每一行的元素。
  2. 再对每一行元素进行修整,使其美观对齐。

分步骤

一、根据需要选出每行的元素

    首先获取我们需要的元素、和我们目标容器的宽度。

Vue组件容器:

<template>
  <div ref="barrel">

      <slot></slot>

  </div>
</template>

二、再者我们需要获取容器和容器宽度

this.barrelBox = this.$refs.barrel;

this.barrelWidth = this.barrelBox.offsetWidth;
    
三、接着循环我们的元素,根据不同的元素的宽度进行分组。
ps:对于元素的宽度获取的时候我们需要对盒模型进行区分。

Array.prototype.forEach.call(items, (item) => {

            paddingRight = 0;

            paddingLeft = 0;

            marginLeft = parseInt(window.getComputedStyle(item, "").getPropertyValue('margin-left'));

            marginRight = parseInt(window.getComputedStyle(item, "").getPropertyValue('margin-right'));

            let boxSizing = window.getComputedStyle(item, "").getPropertyValue('box-sizing');

            if (boxSizing !== 'border-box') {

                paddingRight = parseInt(window.getComputedStyle(item, "").getPropertyValue('padding-right'));

                paddingLeft = parseInt(window.getComputedStyle(item, "").getPropertyValue('padding-left'));

            }

            widths = item.offsetWidth + marginLeft + marginRight + 1;

            item.realWidth = item.offsetWidth - paddingLeft - paddingRight + 1;

            let tempWidth = rowWidth + widths;

            if (tempWidth > barrelWidth) {

                dealWidth(rowList, rowWidth, barrelWidth);

                rowList = [item];

                rowWidth = widths;

            } else {
                rowWidth = tempWidth;

                rowList.push(item);

            }

        })
四、接着是对每一组的元素进行合理分配。
const dealWidth = (items, width, maxWidth) => {

let remain = maxWidth - width;

let num = items.length;

let remains = remain % num;

let residue = Math.floor(remain / num);

items.forEach((item, index) => {

    if (index === num - 1) {

        item.style.width = item.realWidth + residue + remains + 'px';

    } else {

        item.style.width = item.realWidth + residue + 'px';

    }

})

}

    我这边是采用的平均分配的方式将多余的宽度平均分配到每一个元素里。如一行中全部元素占800px,有8个元素,该行总长为960px。则每行增加的宽度为(960-800)/8=16,每个与元素宽度增加16px;
    值得注意的是,js在获取元素宽度的时候会存在精度问题,所以需要进行预设一个像素进行缓冲。

以下是我的代码地址

Github:vue-barrel

npm: vue-barrel

脚本宝典总结

以上是脚本宝典为你收集整理的Vue木桶布局插件全部内容,希望文章能够帮你解决Vue木桶布局插件所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Vue