1.安装
npm install wangeditor --save
2.引入
import E from "wangeditor";
3.新建一个richText.vue的组件,这里包含了如何上传图片,具体代码如下
<template><div id="wangeditor"><div ref="editorElem" style="text-align: left"></div></div></template>
最简单的富文本,基本上三步就可搞定:
import E from 'wangeditor'const editor = new E(this.$refs.editorElem);editor.create()
可添加菜单栏、添加事件
<script>import axios from "axios";import E from "wangeditor";import { getImgLink } from "@/network/more.js";export default {props: {isAdd: {type: String,default: false,},content:{type: String}},data() {return {editor: null,editorContent: "",imgList: [],};},watch: {content:function(){this.editor.txt.html(this.content);}},mounted() {this.getRichText();this.editor.txt.html(this.editorContent);},methods: {getRichText() {var that = this;this.editor = new E(this.$refs.editorElem);this.editor.config.menus = [// 菜单配置"head", // 标题"bold", // 粗体"fontSize", // 字号"fontName", // 字体"italic", // 斜体"underline", // 下划线"strikeThrough", // 删除线"foreColor", // 文字颜色"backColor", // 背景颜色"link", // 插入链接"list", // 列表"justify", // 对齐方式"quote", // 引用"emoticon", // 表情"image", // 插入图片"table", // 表格"code", // 插入代码"undo", // 撤销"redo", // 重复];this.editor.config.showLinkImg = false; //隐藏网络图片上传this.editor.config.uploadImgShowBase64 = true; //图片以base64形式保存this.editor.config.uploadFileName = "file";this.editor.config.customUploadImg = (files, insert) => {let fileName = "";for (let i = 0; i < files.length; i++) {fileName = files[i].name + "," + fileName;}let obj = {fileName: fileName,};// 获取图片链接getImgLink(obj).then((res) => {const code = res.data.code;if (code == 100) {this.imgList = res.data.content;for(let i=0; i<this.imgList.length;i++){//图片回显insert(this.imgList[i])};} else {this.$messsage.error(res.data.message);}}).catch((err) => {console.log(err);});};this.editor.config.onchange = (html) => {this.editorContent = html;//触发父组件的方法,并传值this.$emit("submitHandle", this.editorContent);};this.editor.create(); // 创建富文本实例},},};</script>