編輯庫選擇標準
對于現在的前端編輯庫富文本而言,如果僅從功能上來去看的話,那么其實都是相差無幾的。隨便從 github
中挑選編輯庫,只要 star
在 10K(保守些)
以上的,編輯器之上的常用功能一應俱全。富文本我們使用 wangEditor,因為 wangEditor是國產框架、文檔越詳盡,提供了中文文檔(英文好的可以忽略)、更新快速,不像谷歌開源的markdown-here,github上都好多年沒更新了。
image.png
image.png
所以我們得先去下載 wangEditor
npm i wangeditor@4.7.6
- 我們這里使用的是4.x版本的,當然你也可以使用最新v5版本的,4.x版本我覺得api使用起來更舒服,因人而異吧。安裝完成之后,我們把editor封裝成一個組件,代碼邏輯和注釋如下:
<template>
<div class="editor-container">
<div id="editor-box"></div>
<div class="bottom">
<el-button type="primary" @click="onSubmitClick">提交</el-button>
</div>
</div>
</template>
<script setup>
import E from 'wangeditor'
import { onMounted, defineProps, defineEmits, watch } from 'vue'
import { useStore } from 'vuex'
import conf from "@/utils/config.js";
import {getAdmintorList, publicUploadFile} from "@/api/api";
const props = defineProps({
title: {
required: true,
type: String
},
detail: {
type: Object
}
})
const emits = defineEmits(['onSuccess'])
const store = useStore()
// Editor實例
let editor
// 處理離開頁面切換語言導致 dom 無法被獲取
let el
onMounted(() => {
el = document.querySelector('#editor-box')
initEditor()
})
const initEditor = () => {
editor = new E(el)
editor.config.zIndex = 1
// 菜單欄提示
editor.config.showMenuTooltips = true
editor.config.menuTooltipPosition = 'down'
// 一次最多上傳圖片的數量
editor.config.uploadImgMaxLength = 1;
// 設置編輯區域高度為 500px
editor.config.height = 700
// 限制上傳圖片格式
editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
editor.config.showLinkImg = false
// 默認情況下,顯示所有菜單
editor.config.menus = [
'head',
'bold',
'fontSize',
'fontName',
'italic',
'underline',
'strikeThrough',
'indent',
'lineHeight',
'foreColor',
'backColor',
'link',
'list',
'todo',
'justify',
'quote',
'emoticon',
'image',
// 'video',
'table',
'code',
'splitLine',
'undo',
'redo',
]
// 自定義上傳圖片
editor.config.customUploadImg = (resultFiles, insertImgFn) => {
// resultFiles 是 input 中選中的文件列表
// insertImgFn 是獲取圖片 url 后,插入到編輯器的方法
resultFiles.forEach((item, i) => {
const formData = new FormData()
formData .append('file', item)
publicUploadFile(formData)
.then(res => {
insertImgFn(res.bizobj.src)
})
.catch(err => {
})
})
}
editor.create()
}
// 編輯相關
watch(
() => props.detail,
val => {
if (val && val.content) {
editor.txt.html(val.content)
}
},
{
immediate: true
}
)
const onSubmitClick = async () => {
console.log(editor.txt.html())
editor.txt.html('')
emits('onSuccess')
}
</script>
<style lang="scss" scoped>
.editor-container {
.bottom {
margin-top: 20px;
text-align: right;
}
}
</style>
- 頁面中使用
<template>
<div class="container">
<editor></editor>
</div>
</template>
<script setup>
import Editor from '../components/Editor.vue'
import { ref } from 'vue'
</script>
<style lang="scss" scoped>
.container {
}
</style>
效果
image.png
總結
對于大家而言,不一定非要使用我們在文章中使用的這個編輯器庫。
因為對于編輯器庫而言,它的使用方式都是大同小異的,大家只需要根據我們實際業務需求和使用習慣來選擇使用自己當前情況的編輯器庫即可