富文本编辑器如同我们在CSDN上写文章是的编辑框(如下图),使用场景通常是在编辑详细资料,内容。本次实习过程学习使用了wangeditor,是一个简洁,文档齐全的富文本工具。wangeditor官方文档: /
注:开始时使用V5版本,npm过程无报错,但是在VUE中引入后报错样式包找不到(已引入),随后更替使用V4版本
1.安装以及引入
npm 安装 wangeditorV4版本:
npm i wangeditor@4.x
在VUE页面中引入:
import E from 'wangeditor'
2.使用过程
具体需求:编辑/添加某个产品,出现对话框,对话框中富文本显示产品详情,并且能修改、添加产品详情。
wangeditor的使用是用过DOM获取到某节点元素,在该节点上生成的wangeditor实例。通过 this.editor.config.menus配置 菜单栏,更多配置项见官方文档:
this.editor = new E("#description");this.editor.config.menus = ["head", //标题"foreColor", //字体颜色"bold", //加粗"image", //上传图片"list", //自动排序为有序/无序列表];this.editor.create();
需求中的富文本要在dialog中显示,dialog未渲染时,无法使用Dom获取相关节点。则在mounted生命周期内创建wangeditor将会报错该节点无效。所以只能每次打开dialog时创建wangeditor实例,利用dialog的opened事件即可。
通常富文本编辑器的内容由前端获取到内容的HTML结构,以字符串传给后端接口,储存到数据库。编辑产品时,前端从接口获取富文本字符串,然后解析为HTML插入到富文本编辑器中。在文档接口中,可以直接使用this.editor.txt.html()获取到HTML字符串。
this.editor.txt.html() //获取文本内容字符串
从接口获取HTML字符串显示时,走了个错招,想在富文本编辑器中插入一个DIV使用v-html显示已有的内容,结果在添加新的内容后再使用this.editor.txt.html()获取HTML时会自动复制一份已有内容并显示。后来仔细阅读文档后发现this.editor.txt.html()也可以用来初始化富文本内容。改用此方法后,顺利通过。
this.editor = new E("#description");this.editor.create();this.editor.txt.html('<p>用 JS 设置的内容</p>') //设置文本内容字符串
需要注意的是,不手动清除,内容将永远存留。在每次关闭dialog时,应该将实例的内容清零,并销毁,避免不同产品、不同操作显示情况与数据库内储存内容不一致。同样利用dialog的closed事件:
onclose(){this.editor.txt.html("");this.editor.destroy();this.editor = null;}
完整代码:
HTML
<el-button @click="getData()">open ago dialog</el-button><el-button @click="dialogVisible = true">open new dialog</el-button><el-dialog:visible.sync="dialogVisible"@opened="onOpened()"@closed="onClosed()">//富文本挂载节点<div id="description"></div><span slot="footer" class="dialog-footer"><el-button @click="dialogVisible = false">取 消</el-button><el-button type="primary" @click="send()">确 定</el-button></span> </el-dialog>
JS
export default {data() {return {dialogVisible: false,description: '' }}methods: {//打开dialogonOpened() {//创建新的富文本编辑器, 配置菜单项this.editor = new E("#description");this.editor.config.menus = ["head", //标题"foreColor", //字体颜色"bold", //加粗"image", //上传图片"list", //自动排序为有序/无序列表];this.editor.create();this.editor.txt.html(this.description);},//关闭dialog, 清空数据,销毁实例,避免数据重复 onClosed() {this.editor.txt.html('');this.editor.destroy();this.editor = null;this.description = ''},//模仿获取到接口已经存在的富文本数据,并插入页面async getData(){let data = await api(XXXX) //会先执行getData,然后执行onOpened渲染console.log(data)},//模仿获取文本内容,发送到接口async send(){this.description = this.editor.txt.html(); //获取HTML结构let data = await api(this.description) consloe.log(data)}}}