vue elementui弹框内 富文本编辑器的使用,及踩坑
最近vue项目中遇到弹框内使用富文本编辑器,遇到最大的问题是,在打开弹框后才能创建富文本编辑器,并且只能创建一次,多次点击弹框,报错:
Error in v-on handler: "Error: 初始化节点已存在编辑器实例,无法重复创建编辑器"
经多次查找实验的出如下结论:
首先:选择的 wangeditor 富文本编辑器 :https://www.wangeditor.com/
npm i wangeditor --save
<el-col :span="1.5"> <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['nature:add']" >新增</el-button> </el-col> <el-col :span="1.5"> <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['nature:edit']" >修改</el-button> </el-col>
<!-- 添加或修改 --> <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body> <el-form ref="form" :model="form" :rules="rules" label-width="80px"> <el-form-item label="内容" class="editorMenu"> <div ref="editorElem" id="ids"></div> //此处是富文本编辑器 </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button type="primary" @click="submitForm">确 定</el-button> <el-button @click="cancel">取 消</el-button> </div> </el-dialog>
import E from 'wangeditor'; let editor; methods: { creatDom(){ editor = new E(this.$refs.editorElem)//富文本编辑器创建,获取节点 editor.create();//创建。 }, /** 新增按钮操作 */ handleAdd() { this.reset(); this.open = true; this.nav=1 this.title = "添加案由"; //由于只有在弹窗启动之后,div节点才会被创建,那么创建富文本编辑器也只能在其之后。 this.$nextTick(()=>{ if (editor==null){ this.creatDom(); }else { editor.destroy();//这里做了一次判断,判断编辑器是否被创建,如果创建了就先销毁。 this.creatDom(); } }); }, /** 修改按钮操作 */ handleUpdate(row) { this.nav=2 this.reset(); const postId = row.id || this.ids getNature(postId).then(response => { this.form = response.data; this.open = true; this.title = "修改类型"; this.$nextTick(()=>{ if (editor==null){ this.creatDom(); //editor.txt.html(row.content); }else { editor.destroy();//这里做了一次判断,判断编辑器是否被创建,如果创建了就先销毁。 this.creatDom(); editor.txt.html(row.content); } }); }); }, /** 提交按钮 */ submitForm: function() { // var content = this.editor.txt.text() this.$refs["form"].validate(valid => { if (valid) { if (this.form.id != undefined) { this.form.content = editor.txt.text() //富文本编辑内输入的内容 updateNature(this.form).then(response => { this.$modal.msgSuccess("修改成功"); this.open = false; this.getList(); }); } else { this.form.content = editor.txt.text() addNature(this.form).then(response => { this.$modal.msgSuccess("新增成功"); this.open = false; this.getList(); }); } } }); }, }