index.vue 2.0 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2
<script>
const SPACE_UNICODE = {
fxy060608's avatar
fxy060608 已提交
3 4 5
  ensp: '\u2002',
  emsp: '\u2003',
  nbsp: '\u00a0'
fxy060608's avatar
fxy060608 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
}

export default {
  name: 'Text',
  props: {
    selectable: {
      type: [Boolean, String],
      default: false
    },
    space: {
      type: String,
      default: ''
    },
    decode: {
      type: [Boolean, String],
      default: false
    }
  },
  methods: {
    _decodeHtml (htmlString) {
      if (this.space && SPACE_UNICODE[this.space]) {
        htmlString = htmlString.replace(/ /g, SPACE_UNICODE[this.space])
      }

      if (this.decode) {
        htmlString = htmlString.replace(/&nbsp;/g, SPACE_UNICODE.nbsp).replace(/&ensp;/g, SPACE_UNICODE.ensp).replace(
          /&emsp;/g, SPACE_UNICODE.emsp).replace(/&lt;/g,
          '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&apos;/g, "'")
      }

      return htmlString
    }
  },
  render (createElement) {
    const nodeList = []
    this.$slots.default && this.$slots.default.forEach(vnode => {
      if (vnode.text) {
X
xiaoyucoding 已提交
43
        // 处理可能出现的多余的转义字符
fxy060608's avatar
fxy060608 已提交
44
        const nodeText = vnode.text.replace(/\\n/g, '\n')
45
        const texts = nodeText.split('\n')
fxy060608's avatar
fxy060608 已提交
46
        texts.forEach((text, index) => {
47
          nodeList.push(this._decodeHtml(text))
fxy060608's avatar
fxy060608 已提交
48 49 50 51
          if (index !== (texts.length - 1)) {
            nodeList.push(createElement('br'))
          }
        })
52
      } else {
53
        if (vnode.componentOptions && vnode.componentOptions.tag !== 'v-uni-text') {
Q
qiang 已提交
54
          console.warn('Do not nest other components in the text component, as there may be display differences on different platforms.')
55
        }
fxy060608's avatar
fxy060608 已提交
56 57 58 59
        nodeList.push(vnode)
      }
    })
    return createElement('uni-text', {
X
xiaoyucoding 已提交
60 61 62 63
      on: this.$listeners,
      attrs: {
        selectable: !!this.selectable
      }
fxy060608's avatar
fxy060608 已提交
64 65 66 67 68 69 70 71
    }, [
      createElement('span', {}, nodeList)
    ])
  }
}
</script>
<style>
	uni-text[selectable] {
X
xiaoyucoding 已提交
72
    cursor: auto;
fxy060608's avatar
fxy060608 已提交
73 74 75
		user-select: text;
		-webkit-user-select: text;
	}
Q
qiang 已提交
76
</style>