安裝依賴(lài)組件
yarn add wangeditor
添加全局組件
<template lang="html">
<div class="editor">
<div ref="toolbar" class="toolbar">
</div>
<div ref="editor" class="text">
</div>
</div>
</template>
<script>
import E from 'wangeditor'
export default {
name: 'Editorbar',
data () {
return {
editor: null,
info_: null,
uploadHeader: { 'Authorization': 'Bearer' + localStorage.token, contentType: 'multipart/form-data; charset=UTF-8' }
}
},
props: ['content'],
watch: {
content (newOne, oldOne) {
this.editor.txt.html(newOne)
}
},
mounted () {
this.seteditor()
},
methods: {
seteditor () {
this.editor = new E(this.$refs.toolbar, this.$refs.editor)
this.editor.customConfig.uploadImgShowBase64 = true // base 64 存儲(chǔ)圖片
this.editor.customConfig.uploadImgServer = '/api/upload'// 配置服務(wù)器端地址
this.editor.customConfig.uploadImgHeaders = this.uploadHeader
this.editor.customConfig.uploadFileName = 'file' // 后端接受上傳文件的參數(shù)名
this.editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024 // 將圖片大小限制為 2M
this.editor.customConfig.uploadImgMaxLength = 6 // 限制一次最多上傳 3 張圖片
this.editor.customConfig.uploadImgTimeout = 3 * 60 * 1000 // 設(shè)置超時(shí)時(shí)間
// 配置菜單
this.editor.customConfig.menus = [
'head', // 標(biāo)題
'bold', // 粗體
'fontSize', // 字號(hào)
'fontName', // 字體
'underline', // 下劃線(xiàn)
'foreColor', // 文字顏色
'link', // 插入鏈接
'list', // 列表
'justify', // 對(duì)齊方式
'image', // 插入圖片
'table', // 表格
'undo', // 撤銷(xiāo)
'redo' // 重復(fù)
]
this.editor.customConfig.uploadImgHooks = {
fail: (xhr, editor, result) => {
// 插入圖片失敗回調(diào)
},
success: (xhr, editor, result) => {
// 圖片上傳成功回調(diào)
},
timeout: (xhr, editor) => {
// 網(wǎng)絡(luò)超時(shí)的回調(diào)
},
error: (xhr, editor) => {
// 圖片上傳錯(cuò)誤的回調(diào)
},
customInsert: (insertImg, result, editor) => {
// 圖片上傳成功齐疙,插入圖片的回調(diào)
var url = result.data
insertImg(url)
}
}
this.editor.customConfig.onchange = (html) => {
this.info_ = html // 綁定當(dāng)前逐漸地值
this.$emit('on-change', this.info_) // 將內(nèi)容同步到父組件中
}
// 創(chuàng)建富文本編輯器
this.editor.create()
}
}
}
</script>
<style lang="less">
.editor {
width: 100%;
margin: 0 auto;
}
.toolbar {
border: 1px solid #ccc;
}
.text {
border: 1px solid #ccc;
height: 500px;
}
</style>
使用的父組件頁(yè)面
<editor-bar v-model="model.content" :content="model.content" @on-change="change"></editor-bar>
import EditorBar from '@/components/EditorBar'
OK,到這里就可以正常使用了