{{ showContent }}
当前位置:   article > 正文

vue中文本超出显示省略号最优方案_vue text省略

vue text省略
  1. <template>
  2. <div class="ellipsis-container">
  3. <div class="textarea-container" ref="shadow">
  4. <textarea :rows="rows" readonly tabindex="-1"></textarea>
  5. </div>
  6. {{ showContent }}
  7. <slot name="ellipsis" v-if="(textLength < content.length) || btnShow">
  8. {{ ellipsisText }}
  9. <span class="ellipsis-btn" @click="clickBtn">{{ btnText }}</span>
  10. </slot>
  11. </div>
  12. </template>
  13. <script>
  14. import resizeObserver from 'element-resize-detector'
  15. const observer = resizeObserver()
  16. export default {
  17. props: {
  18. content: {
  19. type: String,
  20. default: ''
  21. },
  22. btnText: {
  23. type: String,
  24. default: '展开'
  25. },
  26. ellipsisText: {
  27. type: String,
  28. default: '...'
  29. },
  30. rows: {
  31. type: Number,
  32. default: 6
  33. },
  34. btnShow: {
  35. type: Boolean,
  36. default: false
  37. },
  38. },
  39. data () {
  40. return {
  41. textLength: 0,
  42. beforeRefresh: null
  43. }
  44. },
  45. computed: {
  46. showContent () {
  47. const length = this.beforeRefresh ? this.content.length : this.textLength
  48. return this.content.substr(0, this.textLength)
  49. },
  50. watchData () { // 用一个计算属性来统一观察需要关注的属性变化
  51. return [this.content, this.btnText, this.ellipsisText, this.rows, this.btnShow]
  52. }
  53. },
  54. watch: {
  55. watchData: {
  56. immediate: true,
  57. handler () {
  58. this.refresh()
  59. }
  60. },
  61. },
  62. mounted () {
  63. // 监听尺寸变化
  64. observer.listenTo(this.$refs.shadow, () => this.refresh())
  65. },
  66. beforeDestroy () {
  67. observer.uninstall(this.$refs.shadow)
  68. },
  69. methods: {
  70. refresh () { // 计算截取长度,存储于textLength中
  71. this.beforeRefresh && this.beforeRefresh()
  72. let stopLoop = false
  73. this.beforeRefresh = () => stopLoop = true
  74. this.textLength = this.content.length
  75. const checkLoop = (start, end) => {
  76. if (stopLoop || start + 1 >= end) return
  77. const rect = this.$el.getBoundingClientRect()
  78. const shadowRect = this.$refs.shadow.getBoundingClientRect()
  79. const overflow = rect.bottom > shadowRect.bottom
  80. overflow ? (end = this.textLength) : (start = this.textLength)
  81. this.textLength = Math.floor((start + end) / 2)
  82. this.$nextTick(() => checkLoop(start, end))
  83. }
  84. this.$nextTick(() => checkLoop(0, this.textLength))
  85. },
  86. // 展开按钮点击事件向外部emit
  87. clickBtn (event) {
  88. this.$emit('click-btn', event)
  89. },
  90. }
  91. }
  92. </script>

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/91703
推荐阅读
相关标签