vue富文本vue-quill-editor實現點擊插入條件


前言:vue-quill-editor心得總結。

  • 基礎用法
  • 顯示問題(回顯格式不正確)
  • 插入帶顏色字符后 光標顏色改變,后續字體顏色隨之變化
  • 實現點擊富文本外條件列表,自動在富文本中插入,及之后的條件回填

1.安裝並引入

下載包並在mian.ts中引入 vue-amap

npm install vue-quill-editor
import VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
Vue.use(VueQuillEditor)

在template中

  <quill-editor v-model="tempContent" :options="editorOption" ref="myQuillEditor" />

在script中

  //data 中
  editorOption= [
    ['bold'], // 加粗 斜體 下划線 刪除線
    [{ indent: '-1' }, { indent: '+1' }], // 縮進
  ],
  tempContent:"富文本中默認內容"

2.常見問題

1)富文本內容傳給服務端后,在別的地方回顯的時候,格式顯示錯誤 如 空格

  //解決辦法   在要顯示的地方 加上 ql-editor 這個類名
    <div v-html="checkData.data[0].content" class="ql-editor"></div>

2)在富文本中插入帶格式內容,該格式會影響之后輸入的文本 如顏色 加粗等

 //問題出現原因 是因為quill富文本會根據當前光標之前有格式的文本來給之后的文本添加樣式,所以 通過插入一個帶格式的空格去解決
     var num = _this.$refs.myQuillEditor.quill.selection.savedRange.index     //獲取富文本中光標位置
     //以下參數分別為  num富文本中光標位置 data要插入的文本   { color: 'rgb(230, 0, 0)' } 新插入文本的顏色
     _this.$refs.myQuillEditor.quill.insertText(num, data, { color: 'rgb(230, 0, 0)' })   
     _this.$refs.myQuillEditor.quill.insertText(num + data.length, ' ', { color: 'rgba(0, 0, 0, 0.65)' })
     _this.$refs.myQuillEditor.quill.selection.savedRange.index = num + data.length + 1   //將光標移到插入的文本(+1 為帶格式空格的長度)之后

3.實現業務功能

產品的需求為 通過點擊左側列表,在富文本中插入對應的條件,然后在其它的頁面篩選出條件,並將條件替換為具體數據

     <ul>
           <li v-for="(item, index) in arr" :key="index" v-html="item" @click="addCondition(item)"></li>
     </ul>
     <quill-editor v-model="tempContent" :options="editorOption" ref="myQuillEditor" />

 //富文本會記錄之前光標位置,在點擊了別的地方后,還是可以獲取到光標位置
  mounted() {
   //使用事件捕獲  
   window.addEventListener('click', this.cancelQuill, true)
 },
   methods: {
   //點擊非富文本區域
   cancelQuill(e: any) {
     if (e.target.nodeName !== 'LI') {
       this.Flag = false
     }
   },
   //富文本插入
   addCondition(data: any) {
     var _this: any = this
     if (!this.Flag)  return
       var num = _this.$refs.myQuillEditor.quill.selection.savedRange.index     
       _this.$refs.myQuillEditor.quill.insertText(num, data, { color: 'rgb(230, 0, 0)' })   
       _this.$refs.myQuillEditor.quill.insertText(num + data.length, ' ', { color: 'rgba(0, 0, 0, 0.65)' })
       _this.$refs.myQuillEditor.quill.selection.savedRange.index = num + data.length + 1   
   }
 },
 beforeDestroy() {
   window.removeEventListener('click', this.cancelQuill, true)
 }

 //別的頁面回顯的時候 直接字符串查找 比如'<span style="color: rgb(230, 0, 0);">{處理結果}</span>' 然后替換成對應的數據

效果展示

因展示需要,代碼略有刪減,若功能不能實現或者其他問題 歡迎私信交流


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM