富文本编辑器-WangEditor
vue2 + WangEditor
引入WangEditor
npm install wangeditor --save
富文本编辑器组件:WangEditor.vue
<template>
<!-- 富文本编辑器组件 -->
<div>
<div ref="editor" style="text-align: left;"></div>
</div>
</template>
<script>
import E from 'wangeditor';
export default {
name: 'WangEditor',
data() {
return {
editor: null, // WangEditor 实例
};
},
props: {
content: {
type: String,
default: ''
}
},
watch: {
// 当父组件传入的 content 变化时,更新编辑器内容
content(newContent) {
if (this.editor && newContent !== this.editor.txt.html()) {
this.editor.txt.html(newContent);
}
}
},
mounted() {
// 初始化 WangEditor
this.editor = new E(this.$refs.editor);
this.editor.config.onchange = () => {
// 编辑器内容变化时,触发 input 事件传递给父组件
this.$emit('input', this.editor.txt.html());
};
// 配置菜单和其他设置
this.editor.config.menus = [
'head', // 标题
'bold', // 粗体
'italic', // 斜体
'underline', // 下划线
'image', // 图片
'link', // 链接
'list', // 列表
'undo', // 撤销
'redo', // 重做
];
this.editor.config.zIndex = 1000;
// 创建编辑器
this.editor.create();
// 设置初始内容
if (this.content) {
this.editor.txt.html(this.content);
}
},
beforeDestroy() {
// 销毁编辑器实例,释放资源
if (this.editor) {
this.editor.destroy();
}
}
};
</script>
<style scoped>
</style>
使用组件
<template>
<div>
<!-- 发布博客 -->
<el-main>
<el-card shadow="never" style="height: 870px;">
<br>
<WangEditor v-model="editorContent" />
<el-divider>↓ 内容预览 ↓</el-divider>
<el-card shadow="never" style="height: 400px;">
<div>
<div v-html="editorContent"></div>
</div>
</el-card>
</el-card>
</el-main>
</div>
</template>
<script>
import WangEditor from '../../WangEditor.vue'
export default {
name: 'blogs',
components: {
WangEditor
},
data() {
return {
editorContent: '<p>快来发布你的博客吧!</p>' // 初始化编辑器内容
}
}
}
</script>
<style scoped>
.el-main {
background-color: white;
color: #333;
text-align: center;
line-height: 20px;
}
</style>
参考————
https://blog.csdn.net/2202_75337835/article/details/141932447

浙公网安备 33010602011771号