溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

el-menu如何實(shí)現(xiàn)橫向溢出截取

發(fā)布時(shí)間:2022-06-01 13:49:29 來(lái)源:億速云 閱讀:476 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹了el-menu如何實(shí)現(xiàn)橫向溢出截取的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇el-menu如何實(shí)現(xiàn)橫向溢出截取文章都會(huì)有所收獲,下面我們一起來(lái)看看吧。

el-menu如何實(shí)現(xiàn)橫向溢出截取

antd的menu組件,會(huì)在subMenu超出的情況下對(duì)超出的subMenu進(jìn)行截取。 但是element的menu組件不會(huì)對(duì)溢出進(jìn)行截取

el-menu如何實(shí)現(xiàn)橫向溢出截取

于是我想對(duì)element的menu再次進(jìn)行封裝,讓它能夠支持寬度溢出截取。

思考

查看了antd的源碼,還是比較復(fù)雜的,他會(huì)對(duì)每一個(gè)subMenu進(jìn)行一份拷貝,然后隱藏在對(duì)應(yīng)subMenu的后邊,然后依賴于resize-observer-polyfill對(duì)menu和subMenu進(jìn)行監(jiān)聽(tīng),然后計(jì)算超出的subMenu下標(biāo)。代碼量還是比較多的,看到最后有點(diǎn)迷糊。
后來(lái)我進(jìn)行了一些思考,需求大概如下

  • 通過(guò)resize-observer-polyfill對(duì)頁(yè)面變化進(jìn)行監(jiān)聽(tīng)

  • 計(jì)算寬度是否溢出,以及subMenu下標(biāo)lastVisbileIndex是多少

  • 渲染出溢出的subMenu集合

  • 底層還是使用el-menu

代碼部分

<template>
  <el-menu
    class="sweet-menu"
    v-bind="$attrs"
    v-on="$listeners"
 >
    <!-- 傳入的menu  -->
    <slot />
    <!-- ...按鈕 -->
    <sub-menu v-if="ellipsis" :list="overflowedElements" />
  </el-menu>
</template>

首先確定template部分 僅僅是需要將傳入的參數(shù)透?jìng)鹘oel-menu,然后通過(guò)默認(rèn)插槽的形式接收傳入的子元素。最后渲染出溢出部分的展示開(kāi)關(guān)。

//subMenu組件
export default {
  props: {
    list: {},
  },
  render(h) {
    return h('template', [
        h('el-submenu', {
        attrs: {
            key: 'overflow-menu',
            index: 'overflow-menu',
            'popper-append-to-body': true,
        },
        class: {
            'overflow-btn': true,
        },
    }, [
        h('span', { slot: 'title' }, '...'),
        ...this.list,
    ]),
    ]);
  },
};

subMenu組件的主要作用是渲染出傳入的list,list其實(shí)就是一段從$slots.default中拿到的VNode列表。

import ResizeObserver from 'resize-observer-polyfill';
import subMenu from './subMenu.vue';
import { setStyle, getWidth, cloneElement } from './utils';
//偏差部分
const FLOAT_PRECISION_ADJUST = 0.5;
export default {
  name: 'SweetMenu',
  components: {
    subMenu,
  },
  data() {
    return {
      // 所有menu寬度總和
      originalTotalWidth: 0,
      resizeObserver: null,
      // 最后一個(gè)可展示menu的下標(biāo)
      lastVisibleIndex: undefined,
      // 溢出的subMenus
      overflowedItems: [],
      overflowedElements: [],
      // 所有menu寬度集合
      menuItemSizes: [],
      lastChild: undefined,
      // 所有menu集合
      ulChildrenNodes: [],
      // 原始slots.defaule備份
      originSlots: [],
    };
  },
  computed: {
    ellipsis() {
      return this.$attrs?.mode === 'horizontal';
    },
  },
  mounted() {
    if (!this.ellipsis) return;
    // 備份slots.default
    this.originSlots = this.$slots.default.map((vnode) => cloneElement(vnode));
    // 拿到...按鈕
    // eslint-disable-next-line prefer-destructuring
    this.lastChild = [].slice.call(this.$el.children, -1)[0];
    // 拿到所有l(wèi)i
    this.ulChildrenNodes = [].slice.call(this.$el.children, 0, -1);
    // 保存每個(gè)menu的寬度
    this.menuItemSizes = [].slice
      .call(this.ulChildrenNodes)
      .map((c) => getWidth(c));
    // 計(jì)算menu寬度總和
    this.originalTotalWidth = this.menuItemSizes.reduce(
      (acc, cur) => acc + cur,
      0,
    );
    // 注冊(cè)監(jiān)聽(tīng)事件
    this.$nextTick(() => {
      this.setChildrenWidthAndResize();
      if (this.$attrs.mode === 'horizontal') {
        const menuUl = this.$el;
        if (!menuUl) return;
        this.resizeObserver = new ResizeObserver((entries) => {
          entries.forEach(this.setChildrenWidthAndResize);
        });
        this.resizeObserver.observe(menuUl);
      }
    });
  },
  methods: {
    setChildrenWidthAndResize() {
      if (this.$attrs.mode !== 'horizontal' || !this.$el) return;
      const { lastChild, ulChildrenNodes } = this;
      // ...按鈕的寬度
      const overflowedIndicatorWidth = getWidth(lastChild);
      if (!ulChildrenNodes || ulChildrenNodes.length === 0) {
        return;
      }
      // 拿到所有slots.default
      this.$slots.default = this.originSlots.map((vnode) => cloneElement(vnode));
      // 解決內(nèi)容區(qū)撐開(kāi)ul寬度問(wèn)題
      ulChildrenNodes.forEach((c) => {
        setStyle(c, 'display', 'none');
      });
      // 獲取el-menu寬度
      const width = getWidth(this.$el);
      // 可展示menu寬度總和
      let currentSumWidth = 0;
      // 最后一個(gè)可展示menu的下標(biāo)
      let lastVisibleIndex;
      // 如果寬度溢出
      if (this.originalTotalWidth > width + FLOAT_PRECISION_ADJUST) {
        lastVisibleIndex = -1;
        this.menuItemSizes.forEach((liWidth) => {
          currentSumWidth += liWidth;
          if (currentSumWidth + overflowedIndicatorWidth <= width) {
            lastVisibleIndex += 1;
          }
        });
      }
      this.lastVisibleIndex = lastVisibleIndex;
      // 過(guò)濾menu相關(guān)dom
      this.overflowedItems = [].slice
        .call(ulChildrenNodes)
        .filter((c, index) => index > lastVisibleIndex);
      this.overflowedElements = this.$slots.default.filter(
        (c, index) => index > lastVisibleIndex,
      );
      // 展示所有l(wèi)i
      ulChildrenNodes.forEach((c) => {
        setStyle(c, 'display', 'inline-block');
      });
      // 對(duì)溢出li隱藏
      this.overflowedItems.forEach((c) => {
        setStyle(c, 'display', 'none');
      });
      // 判斷是否需要顯示...
      setStyle(
        this.lastChild,
        'display',
        lastVisibleIndex === undefined ? 'none' : 'inline-block',
      );
      // 去除隱藏的menu 解決hover時(shí) 被隱藏的menu彈窗同時(shí)出現(xiàn)問(wèn)題
      this.$slots.default = this.$slots.default.filter((vnode, index) => index <= lastVisibleIndex);
    },
  },
};

在js部分,主要是對(duì)subMenu寬度進(jìn)行了判斷,通過(guò)menuItemSizes保存所有subMenu的寬度,然后拿到this.$el也就是容器ul的寬度。通過(guò)遞增的方式,判斷是否溢出,然后記錄lastVisibleIndex。這里需要注意的就是記得要加上最后一個(gè)subMenu的寬度

然后是一些css樣式的處理

.sweet-menu {
  overflow: hidden;
  position: relative;
  white-space: nowrap;
  width: 100%;
  ::v-deep & > .el-menu-item {
    position: relative;
  }
  ::v-deep .overflow-btn {
    .el-submenu__icon-arrow {
      display: none;
    }
  }
  ::v-deep .sweet-icon {
    margin-right: 0.5rem;
  }
}

這里我們只是對(duì)horizontal模式進(jìn)行了處理,vertical模式還是兼容的,所以只需要像使用el-menu的方式進(jìn)行使用 就可以了

//utils.js部分
import classNames from 'classnames';

const camelizeRE = /-(\w)/g;
const camelize = (str) => str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));

export function isEmptyElement(c) {
    return !(c.tag || (c.text && c.text.trim() !== ''));
}
const filterEmpty = (children = []) => children.filter((c) => !isEmptyElement(c));
// eslint-disable-next-line default-param-last
const parseStyleText = (cssText = '', camel) => {
    const res = {};
    const listDelimiter = /;(?![^(]*\))/g;
    const propertyDelimiter = /:(.+)/;
    cssText.split(listDelimiter).forEach((item) => {
        if (item) {
            const tmp = item.split(propertyDelimiter);
            if (tmp.length > 1) {
                const k = camel ? camelize(tmp[0].trim()) : tmp[0].trim();
                res[k] = tmp[1].trim();
            }
        }
    });
    return res;
};
function cloneVNodes(vnodes, deep) {
    const len = vnodes.length;
    const res = new Array(len);
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < len; i++) {
        // eslint-disable-next-line no-use-before-define
        res[i] = cloneVNode(vnodes[i], deep);
    }
    return res;
}

const cloneVNode = (vnode, deep) => {
    const { componentOptions } = vnode;
    const { data } = vnode;
    let listeners = {};
    if (componentOptions && componentOptions.listeners) {
        listeners = { ...componentOptions.listeners };
    }

    let on = {};
    if (data && data.on) {
        on = { ...data.on };
    }
    const cloned = new vnode.constructor(
        vnode.tag,
        data ? { ...data, on } : data,
        vnode.children,
        vnode.text,
        vnode.elm,
        vnode.context,
        componentOptions ? { ...componentOptions, listeners } : componentOptions,
        vnode.asyncFactory,
    );
    cloned.ns = vnode.ns;
    cloned.isStatic = vnode.isStatic;
    cloned.key = vnode.key;
    cloned.isComment = vnode.isComment;
    cloned.fnContext = vnode.fnContext;
    cloned.fnOptions = vnode.fnOptions;
    cloned.fnScopeId = vnode.fnScopeId;
    cloned.isCloned = true;
    if (deep) {
        if (vnode.children) {
            cloned.children = cloneVNodes(vnode.children, true);
        }
        if (componentOptions && componentOptions.children) {
            componentOptions.children = cloneVNodes(componentOptions.children, true);
        }
    }
    return cloned;
};
// eslint-disable-next-line default-param-last
const cloneElement = (n, nodeProps = {}, deep) => {
    let ele = n;
    if (Array.isArray(n)) {
        // eslint-disable-next-line prefer-destructuring
        ele = filterEmpty(n)[0];
    }
    if (!ele) {
        return null;
    }
    const node = cloneVNode(ele, deep);
    // // 函數(shù)式組件不支持clone  https://github.com/vueComponent/ant-design-vue/pull/1947
    // warning(
    //   !(node.fnOptions && node.fnOptions.functional),
    // );
    const {
        props = {}, key, on = {}, nativeOn = {}, children, directives = [],
    } = nodeProps;
    const data = node.data || {};
    let cls = {};
    let style = {};
    const {
        attrs = {},
        ref,
        domProps = {},
        style: tempStyle = {},
        class: tempCls = {},
        scopedSlots = {},
    } = nodeProps;

    if (typeof data.style === 'string') {
        style = parseStyleText(data.style);
    } else {
        style = { ...data.style, ...style };
    }
    if (typeof tempStyle === 'string') {
        style = { ...style, ...parseStyleText(style) };
    } else {
        style = { ...style, ...tempStyle };
    }

    if (typeof data.class === 'string' && data.class.trim() !== '') {
        data.class.split(' ').forEach((c) => {
            cls[c.trim()] = true;
        });
    } else if (Array.isArray(data.class)) {
        classNames(data.class)
            .split(' ')
            .forEach((c) => {
                cls[c.trim()] = true;
            });
    } else {
        cls = { ...data.class, ...cls };
    }
    if (typeof tempCls === 'string' && tempCls.trim() !== '') {
        tempCls.split(' ').forEach((c) => {
            cls[c.trim()] = true;
        });
    } else {
        cls = { ...cls, ...tempCls };
    }
    node.data = {
        ...data,
        style,
        attrs: { ...data.attrs, ...attrs },
        class: cls,
        domProps: { ...data.domProps, ...domProps },
        scopedSlots: { ...data.scopedSlots, ...scopedSlots },
        directives: [...(data.directives || []), ...directives],
    };

    if (node.componentOptions) {
        node.componentOptions.propsData = node.componentOptions.propsData || {};
        node.componentOptions.listeners = node.componentOptions.listeners || {};
        node.componentOptions.propsData = { ...node.componentOptions.propsData, ...props };
        node.componentOptions.listeners = { ...node.componentOptions.listeners, ...on };
        if (children) {
            node.componentOptions.children = children;
        }
    } else {
        if (children) {
            node.children = children;
        }
        node.data.on = { ...(node.data.on || {}), ...on };
    }
    node.data.on = { ...(node.data.on || {}), ...nativeOn };

    if (key !== undefined) {
        node.key = key;
        node.data.key = key;
    }
    if (typeof ref === 'string') {
        node.data.ref = ref;
    }
    return node;
};
const getWidth = (elem) => {
    let width = elem && typeof elem.getBoundingClientRect === 'function' && elem.getBoundingClientRect().width;
    if (width) {
        width = +width.toFixed(6);
    }
    return width || 0;
};
const setStyle = (elem, styleProperty, value) => {
    if (elem && typeof elem.style === 'object') {
        elem.style[styleProperty] = value;
    }
};
export {
    cloneElement,
    setStyle,
    getWidth,
};

關(guān)于“el-menu如何實(shí)現(xiàn)橫向溢出截取”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“el-menu如何實(shí)現(xiàn)橫向溢出截取”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI