【vue2】封装文字过长自动省略部分并且鼠标悬浮显示全部

技术:Ant design vue1.7.8 UI框架、vue2.X

需求:实现文字过长自动省略部分,鼠标悬浮显示全部

效果图
图一:

【vue2】封装文字过长自动省略部分并且鼠标悬浮显示全部_第1张图片
图二:
【vue2】封装文字过长自动省略部分并且鼠标悬浮显示全部_第2张图片

1.封装组件代码:

src/components/Ellipsis/index.js 文件下代码

import Ellipsis from './Ellipsis'

export default Ellipsis

src/components/Ellipsis/Ellipsis.vue 文件下代码

<script>
import Tooltip from 'ant-design-vue/es/tooltip'
import { cutStrByFullLength, getStrFullLength } from '@/components/_util/util'
export default {
  name: 'Ellipsis',
  components: {
    Tooltip
  },
  props: {
    prefixCls: {
      type: String,
      default: 'ant-pro-ellipsis'
    },
    tooltip: {
      type: Boolean
    },
    length: {
      type: Number,
      required: true
    },
    lines: {
      type: Number,
      default: 1
    },
    fullWidthRecognition: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    getStrDom (str, fullLength) {
      return (
        <span>{ cutStrByFullLength(str, this.length) + (fullLength > this.length ? '...' : '') }</span>
      )
    },
    getTooltip (fullStr, fullLength) {
      return (
        <Tooltip>
          <template slot="title">{ fullStr }</template>
          { this.getStrDom(fullStr, fullLength) }
        </Tooltip>
      )
    }
  },
  render () {
    const { tooltip, length } = this.$props
    const str = this.$slots.default.map(vNode => vNode.text).join('')
    const fullLength = getStrFullLength(str)
    const strDom = tooltip && fullLength > length ? this.getTooltip(str, fullLength) : this.getStrDom(str, fullLength)
    return (
      strDom
    )
  }
}
script>

src/components/_util/util.js 文件下代码


/**
 * 获取字符串长度,英文字符 长度1,中文字符长度2
 * @param {*} str
 */
export const getStrFullLength = (str = '') =>
  str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (charCode >= 0 && charCode <= 128) {
      return pre + 1
    }
    return pre + 2
  }, 0)

/**
 * 截取字符串,根据 maxLength 截取后返回
 * @param {*} str
 * @param {*} maxLength
 */
export const cutStrByFullLength = (str = '', maxLength) => {
  let showLength = 0
  return str.split('').reduce((pre, cur) => {
    const charCode = cur.charCodeAt(0)
    if (charCode >= 0 && charCode <= 128) {
      showLength += 1
    } else {
      showLength += 2
    }
    if (showLength <= maxLength) {
      return pre + cur
    }
    return pre
  }, '')
}

2.使用方法

script代码块

import { Ellipsis } from '@/components'
export default {
  components: {
    Ellipsis,
  },
 }

template代码块

 <ellipsis :length="10" tooltip>{{ name }}ellipsis>

你可能感兴趣的:(vue.js)