editArea.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <template>
  2. <div
  3. class="edit-div"
  4. :contenteditable="true"
  5. @focus="handleFocus"
  6. @blur="handleBlur"
  7. @keydown="handleKeyDown"
  8. @input="changeText"
  9. v-html="innerText"
  10. ref="chatInput"
  11. ></div>
  12. </template>
  13. <script>
  14. import { mapState, mapMutations } from 'vuex'
  15. export default {
  16. name: 'editDiv',
  17. props: {
  18. value: {
  19. type: String,
  20. default: ''
  21. }
  22. },
  23. data () {
  24. return {
  25. innerText: this.value,
  26. isLocked: true
  27. }
  28. },
  29. watch: {
  30. value (to, from) {
  31. if (!this.isLocked || !this.innerText) {
  32. this.innerText = this.value
  33. }
  34. },
  35. chatInputFocus (val, newval) {
  36. let ele = this.$refs.chatInput
  37. if (val) {
  38. if (document.activeElement !== ele) {
  39. this.placeEnd(ele)
  40. ele.focus()
  41. // hack--<br>标签光标不换行
  42. if (/(<br>|<\/br>|<\/ br>)$/.test(ele.innerHTML)) {
  43. document.execCommand('insertParagraph', false)
  44. }
  45. }
  46. } else {
  47. if (document.activeElement === ele) {
  48. ele.blur()
  49. }
  50. }
  51. }
  52. },
  53. methods: {
  54. ...mapMutations(['updateChatInputFocus']),
  55. changeText (e) {
  56. this.$emit('input', this.$el.innerHTML)
  57. this.$nextTick(() => {
  58. var range = window.getSelection()
  59. range.selectAllChildren(e.target)
  60. range.collapseToEnd()
  61. })
  62. },
  63. handleFocus () {
  64. this.isLocked = true
  65. },
  66. handleBlur () {
  67. this.isLocked = false
  68. this.updateChatInputFocus(false)
  69. },
  70. handleKeyDown (e) {
  71. var ctrlKey = e.ctrlKey || e.metaKey
  72. if (e.code === 'Enter' && ctrlKey) {
  73. this.$emit('nextLine')
  74. this.$nextTick(() => {
  75. this.placeEnd(e.target)
  76. })
  77. return false
  78. }
  79. // 发送
  80. if (e.code === 'Enter') {
  81. // 阻止换行
  82. this.innerText = ''
  83. e.preventDefault()
  84. this.$emit('sendMsg')
  85. }
  86. },
  87. placeEnd (el) {
  88. var range = document.createRange()
  89. range.selectNodeContents(el)
  90. range.collapse(false)
  91. var sel = window.getSelection()
  92. sel.removeAllRanges()
  93. sel.addRange(range)
  94. }
  95. },
  96. computed: {
  97. ...mapState({
  98. chatInputFocus: state => state.group.chatInputFocus
  99. })
  100. }
  101. }
  102. </script>
  103. <style lang="scss" scoped>
  104. .edit-div {
  105. height: 90px;
  106. line-height: 24px;
  107. overflow-y: auto;
  108. overflow-x: hidden;
  109. padding-left: 20px;
  110. outline: none;
  111. border: 0;
  112. font-size: 14px;
  113. margin: 0;
  114. white-space: pre;
  115. }
  116. </style>