前端在開發時,可能會使用到富文本編輯器,作爲vue項目中,quill是一款不錯的富文本編輯器,但是,它有一個問題,即如果在富文本中添加圖片或視頻時,會將本地的媒體文件轉爲base64,如果我們不處理這些問題時,會使得到的輸入內容過長,一方面網絡加載很慢,另一方面可能會導致後臺在創建數據庫進,內容溢出,所以,無論對前端還是後臺而言,都需要將被保存的文件單獨上傳,將img標籤中src的值替換爲上傳後的地址。
下面我們將從頭開始,實現這個功能,當然,前提我們需要有一個vue前端項目,可以直接使用vue-cli
來創建,也可以直接下載一些搭建好的空白項目,此處略去方法或步驟。
1. 首先:我們在項目中引入quill
。
npm install -S quill
2. 在使用的地方引入quill 根據實際情況引入quill組件及其樣式,可以全局引入,也可以在單個頁面中引入。
// 1. 全局引入,在main.js中引入
import Quill from "quill"
Vue.use(Quill)
import "quill/dist/quill.core.css"
import "quill/dist/quill.snow.css"
import "quill/dist/quill.bubble.css";
// 2. 局部引入,一般會把它封裝爲一個組件,方便多次使用
// 在components/QuillEditor/index.vue中引入quill
import Quill from "quill";
import "quill/dist/quill.core.css"
import "quill/dist/quill.snow.css"
import "quill/dist/quill.bubble.css";
3. 初始化編輯器,配置編輯器
- 在template創建一個富文本的載體div,再創建一個隱藏的input,用於圖片上傳,設置好accept
<div>
<div id="editor" class="eidtor" ref="editor"> </div>
<input type="file" @change="picChange" style="display: none;" id="picInput">
</div>
- 初始化富文本編輯器
import Quill from "quill"
import "quill/dist/quill.core.css"
import "quill/dist/quill.snow.css"
import "quill/dist/quill.bubble.css";
export default {
data() {
return {
quill: null
}
},
mounted() {
// 注意,不要在created中初始化,可能會導致找不到div
this.initEDditor();
},
methods: {
// 配置方法,可以直接寫在data中
getOptions() {
return {
theme: "snow",
debug: "warn",
modules: [
toolbar: [
["bold", "italic", "underline", "strike"], // 加粗 斜體 下劃線 刪除線
["blockquote", "code-block"], // 引用 代碼塊
[{ list: "ordered" }, { list: "bullet" }], // 有序、無序列表
[{ indent: "-1" }, { indent: "+1" }], // 縮進
[{ size: ["small", false, "large", "huge"] }], // 字體大小
[{ header: [1, 2, 3, 4, 5, 6, false] }], // 標題
[{ color: [] }, { background: [] }], // 字體顏色、字體背景顏色
[{ align: [] }], // 對齊方式
["clean"], // 清除文本格式
["link", "image"] // 鏈接、圖片、視頻
]
]
}
},
initEditor() {
let options = this.getOptions();
this.quill = new Quill("#editor", options);
},
}
}
- 添加圖片上傳,並將上傳後得一的url放回到編輯器中對應的img標籤中,當然,在此之前需要下載發送請求的工具,如我們常用的axios。
npm install -S axios
此時的原理是:當我們監聽到點擊上傳圖片時,將我們隱藏的input被點擊,此時,會調起選擇文件的框,當我們選中了文件後,直接使用input的change事件,使用我們寫好的上傳圖片的方法,當圖片上傳成功後,我們調用quill爲我們提供的insertEmbed
方法,將圖片上的路徑存放到這個富文本中,當我們了了解了這個原理後,可以實現視頻上傳了(關於視頻上傳的代碼就不貼出來了)。具體代碼如下:
mounted() {
this.initEDditor();
this.quill.getModule("toolbar").addHandler("image", this.uploadImg)
},
methods: {
uploadImg(e) {
document.getElementId("picInput").click();
},
// 選擇完圖片後
picChange(e) {
let file = e.target.files[0];
let fm = new FormData();
fm.append("file", file);
this.postImg(fm).then(res =>{
// 下面的方法是我從網上查找的資料,也可能是官方提供 的方法,不過可以實現
let addImageRange = this.quill.getSelection();
let newRange = 0 + (addImageRange !== null ? addImageRange.index : 0);
// res.url爲上傳成功後由後臺返回的圖片訪問路徑
this.quill.insertEmbed(newRange, "image", res.url);
this.quill.setSelection(1 + newRange);
})
},
// 圖片上傳接口
postImg(fm) {
let token = getToken(); // 獲取token,根據實際來實現
let headers = {
"Content-Type": "multipart/form-data",
Authorization: "Bearer " + token
}
return new Promise(resolve =>{
axios({
url: "xxx",
method: "post",
data: fm,
headers: headers
})
}).then(res =>{
if (res.data.code == 200) {
resolve(res.data);
} else {
this.$message.error(res.data.msg)
}
}).catch(err =>{
this.$message.error(err.msg || "服務器錯誤,請稍候再試");
})
}
}
- 既然做爲一個組件,得需要回顯數據、向父組件傳值等操作,所以,我們還需要添加上quill爲我們提供好的回調方法和向編輯器傳值的方法
initEditor() {
let options = this.getEditorOptions();
this.quill = new Quill("#editor", options);
this.quill.pasteHTML(this.currentValue);
this.quill.on("text-change", (delta, oldDelta, source) => {
const html = this.$refs.editor.children[0].innerHTML;
const text = this.quill.getText();
const quill = this.quill;
this.currentValue = html;
this.$emit("input", html);
this.$emit("on-change", { html, text, quill });
});
this.quill.on("text-change", (delta, oldDelta, source) => {
this.$emit("on-text-change", delta, oldDelta, source);
});
this.quill.on("selection-change", (range, oldRange, source) => {
this.$emit("on-selection-change", range, oldRange, source);
});
this.quill.on("editor-change", (eventName, ...args) => {
this.$emit("on-editor-change", eventName, ...args);
});
},
// 添加watch監聽,防止因渲染的生命週期方法導致頁面無法回顯數據
watch: {
value: {
handler(val) {
if (val !== this.currentValue) {
this.currentValue = val === null ? "" : val;
if (this.quill) {
this.quill.pasteHTML(this.currentValue);
}
}
}
},
},
如些,我們的editor也算是封裝完成 了,當然 還需要加上上結class樣式,下面是完整的代碼
<template>
<div>
<div id="editor" class="eidtor" ref="editor"></div>
<input type="file" id="picInput" style="display: none;" @change="picChange">
</div>
</template>
<script>
import Quill from "quill"
import "quill/dist/quill.core.css"
import "quill/dist/quill.snow.css"
import "quill/dist/quill.bubble.css";
import axios from 'axios';
export default {
data() {
return {
quill: null,
currentValue: ""
}
},
props: {
/* 編輯器的內容 */
value: {
type: String,
default: "",
},
},
mounted() {
this.initEditor();
this.quill.getModule("toolbar").addHandler("image", this.uploadImage);
},
watch: {
value: {
handler(val) {
if (val !== this.currentValue) {
this.currentValue = val === null ? "" : val;
if (this.Quill) {
this.Quill.pasteHTML(this.currentValue);
}
}
}
},
},
methods: {
// quill的配置內容
getEditorOptions() {
let options = {
debug: "warn",
modules: { // 配置工具欄
toolbar: [
["bold", "italic", "underline", "strike"], // 加粗 斜體 下劃線 刪除線
["blockquote", "code-block"], // 引用 代碼塊
[{ list: "ordered" }, { list: "bullet" }], // 有序、無序列表
[{ indent: "-1" }, { indent: "+1" }], // 縮進
[{ size: ["small", false, "large", "huge"] }], // 字體大小
[{ header: [1, 2, 3, 4, 5, 6, false] }], // 標題
[{ color: [] }, { background: [] }], // 字體顏色、字體背景顏色
[{ align: [] }], // 對齊方式
["clean"], // 清除文本格式
["link", "image"] // 鏈接、圖片、視頻
]
},
placeholder: "請輸入文本內容",
readOnly: false,
theme: "snow" // 官方給定的theme有兩種,一種爲snow:標準工具欄主題;bublle:浮動提示主題
}
return options;
},
// 初始化quill對象
initEditor() {
let options = this.getEditorOptions();
this.quill = new Quill("#editor", options);
this.quill.pasteHTML(this.currentValue);
// 下面的方法按需調用
this.quill.on("text-change", (delta, oldDelta, source) => {
const html = this.$refs.editor.children[0].innerHTML;
const text = this.quill.getText();
const quill = this.quill;
this.currentValue = html;
this.$emit("input", html);
this.$emit("on-change", { html, text, quill });
});
this.quill.on("text-change", (delta, oldDelta, source) => {
this.$emit("on-text-change", delta, oldDelta, source);
});
this.quill.on("selection-change", (range, oldRange, source) => {
this.$emit("on-selection-change", range, oldRange, source);
});
this.quill.on("editor-change", (eventName, ...args) => {
this.$emit("on-editor-change", eventName, ...args);
});
},
// 點擊編輯器中的圖片時觸發的回調方法
uploadImage() {
document.getElementById("picInput").click();
},
// 文件輸入框失去焦點時,觸發的方法
picChange(e) {
let file = e.target.files[0];
let fm = new FormData();
fm.append("file", file);
this.postImg(fm).then(res =>{
// 將返回的可以直接訪問的圖片路徑放回到編輯器中
let url = res.url;
const addImageRange = this.quill.getSelection();
const newRange = 0 + (addImageRange !== null ? addImageRange.index : 0);
this.quill.insertEmbed(newRange,'image' ,url);
this.quill.setSection(1 + newRange);
});
},
// 向後臺提交圖片
postImg(fm) {
return new Promise((resolve, reject) =>{
let self = this;
let headers = {
"Content-Type": "multipart/form-data"
}
// 如果需要token時,需要此時添加token
if (token) {
headers.Authorzation = "Bearer " + token
}
axios({
url: "",
method: "POST",
headers: headers,
data: fm,
})
.then(res =>{
if (res.data.code === 200) {
// 根據實際返回的值進行處理
resolve(res.data);
} else {
self.$message.error(res.data.msg);
}
})
.catch(err =>{
self.$message.error(res.data.msg);
})
})
}
},
};
</script>
<style>
.eidtor {
min-height: 150px;
max-height: 500px;
overflow: auto;
}
.editor, .ql-toolbar {
white-space: pre-wrap!important;
line-height: normal !important;
}
.quill-img {
display: none;
}
.ql-snow .ql-tooltip[data-mode="link"]::before {
content: "請輸入鏈接地址:";
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
border-right: 0px;
content: "保存";
padding-right: 0px;
}
.ql-snow .ql-tooltip[data-mode="video"]::before {
content: "請輸入視頻地址:";
}
.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
content: "14px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
content: "10px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
content: "18px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
content: "32px";
}
.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
content: "文本";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
content: "標題1";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
content: "標題2";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
content: "標題3";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
content: "標題4";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
content: "標題5";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
content: "標題6";
}
.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
content: "標準字體";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
content: "襯線字體";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
content: "等寬字體";
}
</style>
調用的方法:
<QuillEditor v-model="longText" />