在項目中需求在文本框中添加一個鏈接,鏈接的a標簽要帶有href、id、data-value等自定義屬性,但是通過富文本定義的鏈接只能添加href綁定在a標簽上。
之前在百度上面找到類似的文章但是都出現(xiàn)一些小問題,目前都處理ok。在此留個筆記,提提神哈
參考文章:引路文章之vue-quill-editor 如何用insertEmbed插入一個a標簽
代碼實現(xiàn)如下:
<template>
<div class="editor">
<quillEditor v-model="content" ref="rishTextEditor" :options="editorOption" >
<div id="toolbar" slot="toolbar">
<span title="自定義鏈接" class="ql-formats">
<button type="button" @click="customLinkClick" class="ql-link"></button>
</span>
</div>
</quillEditor>
</div>
</template>
<script>
//引入富文本編輯器
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
//引入Qill插件
import Quill from "quill";
var Link = Quill.import("formats/link");
// 自定義a鏈接
class FileBlot extends Link {
// 繼承Link Blot
static create(value) {
let node = undefined;
if (value && !value.href) {
// 適應原本的Link Blot
node = super.create(value);
} else {
// 自定義Link Blot
node = super.create(value.href);
node.innerText = value.innerText;
node.href = value.href;
node.id= value.id;
node.setAttribute("title", value.innerText);
node.setAttribute("data-value", value.dataValue);
}
return node;
}
}
FileBlot.blotName = "link";
FileBlot.tagName = "A";
//注冊FileBlot
Quill.register(FileBlot);
export default {
name: 'editor',
components: { quillEditor },
props: {
value: {
type: String
},
},
data() {
return {
content: null,
editorOption: {
modules: {
toolbar: '#toolbar'
}
}
}
},
methods: {
//顯示自定義鏈接在富文本框上
customLinkClick(){
//獲取焦點
this.editor.focus();
this.editor.insertEmbed(
this.editor.getSelection().index,
"link",
{
href: exportUrl,
innerText: data.title,
id: data.id,
dataValue: data.dataValue,
},
"api"
);
}
},
computed: {
editor() {
return this.$refs.vueQuillEditor.quill;
}
}
}
【其他問題1】 自定義鏈接要如何重新渲染在富文本里呢?
使用innerHTML 渲染,實現(xiàn)如下:
mounted() {
//編輯時進行文本框賦值
this.$refs.rishTextEditor.quill.container.querySelector(
".ql-editor"
).innerHTML = this.value;
}
【其他問題2】解決文本框賦值后獲取焦點
mounted() {
//【富文本的坑】解決文本框賦值后獲取焦點
this.$refs.rishTextEditor.quill.enable(false);
this.$nextTick(function() {
this.$refs.rishTextEditor.quill.enable(true);
this.$refs.rishTextEditor.quill.blur();
});
小棨留言:文章描述或者語法理解不到位的地方,請大家多多指教!