用于通告、用户协议等可编辑的文本内容,要求页面和编辑框内容同步,一开始是思路是编辑时直接在段落盒子上创造一个editor实例,但是发现在保存并销毁实例时会把内容也摧毁掉,所以想了两种解决方法。
1.点击编辑弹出对话框,对话框里是文本内容,保存以后传输到后台并重新查询文本,同时文本内容和编辑器内容一起更新(不需要销毁实例)
2.点击编辑时直接在段落盒子上创造一个editor实例,点击保存发送到后端并销毁实例,利用Vue里面的provide+inject组合进行一个局部刷新(csdn就能搜到方法)
这里介绍第一种
代码
//显示原文
<el-tab-pane label="用户协议" name="second">
<div class="editorContainer" v-loading="loading">
<p v-html="info"></p>
</div>
<span class="editorButton" @click="openEditor">编辑</span>
</el-tab-pane>
</el-tabs>
//点击编辑打开的对话框
<el-dialog
title="修改用户协议"
:visible.sync="dialogVisible"
width="80%"
:before-close="handleClose"
:close-on-press-escape="false"
:close-on-click-modal="false"
@opened="show()"
>
<div ref="editorElem">
<p v-html="info"></p>
</div>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="addProtocol">确 定</el-button>
</span>
</el-dialog>
//引入该实例
import E from "wangeditor";
// methods
//关闭的确认消息
handleClose(done) {
this.$confirm("确认关闭?")
.then(_ => {
done();
})
.catch(_ => {});
},
// 对编辑器进行加载
show() {
//const that = this;
if (!this.isEdit) {
//如果没有创建过,则创建一个编辑器实例
this.editor = new E(this.$refs.editorElem);
// 设置编辑区域高度为 500px
this.editor.config.height = 500;
// editor.config.showFullScreen = false
//创建示例
this.editor.create();
this.isEdit = true;
}
},
//点击编辑打开对话框
openEditor() {
this.dialogVisible = true;
},
//获取用户协议
getProtocol() {
this.loading = true;
API.getProtocol()
.then(response => {
this.loading = false;
this.info = response.data.content;
})
.catch(error => {
this.loading = false;
console.log(error);
});
},
//将富文本编辑器的内容传给后端
addProtocol() {
this.editorContent = this.editor.txt.html();
let obj = {
type: "用户协议",
content: this.editorContent
};
API.addProtocol(obj)
.then(response => {
this.$message.success("操作成功!");
this.dialogVisible = false;
this.getProtocol();
})
.catch(error => {
this.loading = false;
console.log(error);
});
},