前段時間在項目中有這樣一個需求:
1:要求使用者在輸入文字的過程中可以引用變量,并且可以插入到任意的位置。
2:引用的變量要求是一個整體,删除的話必須整體删除。不能在一個變量的中間插入其他的文字。
3:引用的變量和輸入的文字在樣式上也要有差別。
拿到這樣一個需求,第一個想到的就是需要使用富文本編輯器。随後經過調研,選擇了github上start 25k的quill。
下面就來說一個我的使用方案吧。
1:因為項目使用的架構為vue是以下載下傳安裝vue-quill-editor:npm install vue-quill-edito
2:引入到元件中使用,需要以下兩個部分:
- 頭部引入
import { quillEditor} from 'vue-quill-editor';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
- 作為components引入該元件
components: {
QuillEditor: quillEditor,
},
3:這樣就可以在項目中使用quillEditor了。
<QuillEditor
ref="editor"
v-model="desc"
>
到這裡我們就可以使用quill富文本編輯器了,可以給它設定官網上的所有的屬性和方法。官網位址
接下來就是要滿足産品的需求。
1:插入變量。quill提供了可以自定義标簽的方法,具體操作如下:
建立一個js檔案。這裡我取名叫quill.js,自定義的标簽名叫ruleVariates。這個檔案是需要引入到vue元件中。
import { Quill } from 'vue-quill-editor';
const Embed = Quill.import('blots/embed');
// 拿到内嵌
class ruleVariates extends Embed {
static blotName = 'ruleVariates';
static tagName = 'ruleVariates';
static create(value) {
if (!value.split) return super.create('')
let val = value.split(',')
const node = super.create(val[0]);
node.innerHTML = val[0];
node.setAttribute('logType', val[0]);
return node;
}
}
// 注冊
Quill.register(ruleVariates)
我們可以通過setAttribute給這個變量設定屬性,設定的屬性和我們平時使用的class,id是一樣的。
上面我就是給這個自定義标簽設定了logType這個屬性。
2:變量設定好了,那就需要把它插入到設定的位置。
-
擷取要插入到的位置
quill提供了focus這個方法,可以擷取目前的焦點位置。如果沒有焦點的話,就預設是0。但是這裡如果當度使用focus方法是會存在一些問題,必須搭配selection-change方法一起使用。具體原因的話我也不是很清楚。
<QuillEditor
ref="editor"
v-model="desc"
:options="descObj.editorOption"
@selection-change="descFocus"
@focus="descFocus"
>
descFocus(){
const quill = this.$refs['editor'].quill;
this.descRage = quill.getSelection();
},
這個時候descRage的index屬性就是目前的焦點的位置。
- 将變量插入到焦點的位置
addVarToText() {
this.$nextTick(() => {
const quill = this.$refs['editor'].quill;
const range = this.descRage;
let message = '';
if (!range) {
message = '請先點選到文本框!';
} else {
quill.insertEmbed(range.index, 'ruleVariates', 'logType',
}
})
},
這時候這裡的logType就會作為ruleVariates标簽的logType屬性的值。
到這裡我們就已經将功能實作了90%了。因為ruleVariates标簽是一個整體,是以删除的時候整個變量都會被删除。
3: 最後一步,給變量設定樣式。
直接在css中操作就可以啦!
rulevariates {
color: #1596f0;
font-weight: 700;
}
好啦現在就大功告成了。bingo