赞
踩
- <template>
- <div class="ellipsis-container">
- <div class="textarea-container" ref="shadow">
- <textarea :rows="rows" readonly tabindex="-1"></textarea>
- </div>
- {{ showContent }}
- <slot name="ellipsis" v-if="(textLength < content.length) || btnShow">
- {{ ellipsisText }}
- <span class="ellipsis-btn" @click="clickBtn">{{ btnText }}</span>
- </slot>
- </div>
- </template>
-
- <script>
- import resizeObserver from 'element-resize-detector'
- const observer = resizeObserver()
-
- export default {
- props: {
- content: {
- type: String,
- default: ''
- },
- btnText: {
- type: String,
- default: '展开'
- },
- ellipsisText: {
- type: String,
- default: '...'
- },
- rows: {
- type: Number,
- default: 6
- },
- btnShow: {
- type: Boolean,
- default: false
- },
- },
- data () {
- return {
- textLength: 0,
- beforeRefresh: null
- }
- },
- computed: {
- showContent () {
- const length = this.beforeRefresh ? this.content.length : this.textLength
- return this.content.substr(0, this.textLength)
- },
- watchData () { // 用一个计算属性来统一观察需要关注的属性变化
- return [this.content, this.btnText, this.ellipsisText, this.rows, this.btnShow]
- }
- },
- watch: {
- watchData: {
- immediate: true,
- handler () {
- this.refresh()
- }
- },
- },
- mounted () {
- // 监听尺寸变化
- observer.listenTo(this.$refs.shadow, () => this.refresh())
- },
- beforeDestroy () {
- observer.uninstall(this.$refs.shadow)
- },
- methods: {
- refresh () { // 计算截取长度,存储于textLength中
- this.beforeRefresh && this.beforeRefresh()
- let stopLoop = false
- this.beforeRefresh = () => stopLoop = true
- this.textLength = this.content.length
- const checkLoop = (start, end) => {
- if (stopLoop || start + 1 >= end) return
- const rect = this.$el.getBoundingClientRect()
- const shadowRect = this.$refs.shadow.getBoundingClientRect()
- const overflow = rect.bottom > shadowRect.bottom
- overflow ? (end = this.textLength) : (start = this.textLength)
- this.textLength = Math.floor((start + end) / 2)
- this.$nextTick(() => checkLoop(start, end))
- }
- this.$nextTick(() => checkLoop(0, this.textLength))
- },
- // 展开按钮点击事件向外部emit
- clickBtn (event) {
- this.$emit('click-btn', event)
- },
- }
- }
- </script>

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。