vue引入富文本编辑器
1、安装模块
npm i wangeditor@4.7.15 --save
2、导入配置文件 在components文件夹下新建文件 config.js , wLayoutMenu.js ,index.vue
1.config.js
const defaultConfig = {
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', // 恢复
],
fontNames: ['黑体', '仿宋', '楷体', '宋体', '微软雅黑', 'Arial'], // 常用字体
lineHeights: ['1', '1.15', '1.6', '2', '2.5', '3'],
uploadImgAccept: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'], // 限制图片类型
uploadVideoAccept: ['mp4'], // 限制视频类型
}
export default {
defaultConfig,
}
2、wLayoutMenu.js
import E from 'wangeditor'
const {
$, BtnMenu } = E
// 设置默认样式
const initPStyle = 'text-indent: 2em; font-size: 20px !important; line-height: 1.5; font-family: 仿宋'
export default class wLayoutMenu extends BtnMenu {
constructor(editor) {
// data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
const $elem = $('<div class="w-e-menu" style="width: 80px;font-weight: bold;color: #999" data-title="一键排版">一键排版</div>')
super($elem, editor)
}
clickHandler() {
// 获取富文本编辑区的DOM
const childDomArr = this.editor.$textElem.elems[0].childNodes
if (childDomArr.length > 0) {
childDomArr.forEach((item) => {
// 富文本编辑的内容默认外层都是由p标签包容,所以直接在p标签上进行设置默认排版的样式
if (item.nodeName === 'P') {
item.style.cssText = initPStyle
}
if (item.childNodes.length > 0) {
// 遍历找到子元素中存在img标签的内容进行设置默认样式
item.childNodes.forEach((child) => {
if (child.localName === 'img') {
// 获取原图width、height
const width = child.width
const height = child.height
const ratio = width / height
const setW = 600
let setH = 0 // 等比计算
if (setW / setH !== ratio) {
setH = setW / ratio
}
// 给img标签设置行内样式
child.setAttribute('width', setW