下载安装
npm i wangeditor --save
封装组件Editor
- 新建Vue组件Editor
- 初始化编辑器组件
<template lang="html"> <div id="editor"> </div> </template> <script> import E from 'wangeditor' export default { name: 'Editor', data() { return { editor: '' } }, mounted() { const editor = new E("#editor"); this.editor = editor; // 保存创建的实例 editor.create(); } } </script> - 接收父组件传入的富文本内容参数
props: { content: { type: String, default: '' } }, - 监听父组件传入参数的变化,并初始化至编辑器中
watch: { content() { this.editor.txt.html(this.content); } } - 监听编辑器中内容的改变,并同步给父组件传入的参数
通过onchange方法来监听编辑器中内容的变化,但是由于子组件不能直接更改父组件的内容, 我使用$emit方式来触发父组件自定义的方法来修改数据。 在初始化代码中添加: editor.config.onchange = function (newHtml) { if (newHtml) { this.$emit('update:content',newHtml); } }.bind(this) - 父组件调用封装好的Editor组件
引入和注册组件不写了哈 解释一下.sync,它相当于v-on:update:content="article = $event"的简写 <Editor :content.sync="article"></Editor>
最后附上完整代码
<template lang="html">
<div id="editor">
</div>
</template>
<script>
import E from 'wangeditor'
export default {
name: 'Editor',
props: {
content: {
type: String,
default: ''
}
},
data () {
return {
editor: ''
}
},
mounted() {
const editor = new E("#editor");
this.editor = editor;
editor.config.height = 250; // 高度,单位xp
editor.config.zIndex = 500; // z-index属性
editor.config.onchange = function (newHtml) {// 需要改变this指向域
if (newHtml) {
this.$emit('update:content',newHtml);
}
}.bind(this)
editor.config.excludeMenus = [ // 配置使用哪些编辑器功能
'emoticon',
'video',
'todo',
'quote',
'code',
'undo',
'redo'
]
editor.create();
},
methods: {
},
watch: {
content() {
this.editor.txt.html(this.content);
}
}
}
</script>
关于wangeditorV4版本API文档
wangEditor —— 轻量级 web 富文本编辑器,配置方便,使用简单
如果帮到您,不妨点个赞噢铁汁
本文介绍了如何在Vue项目中使用wangeditor4.0,包括下载安装、封装组件Editor以及实现编辑器内容与Vue数据的双向绑定。通过监听组件内外变化,确保编辑器内容与父组件参数同步。

被折叠的 条评论
为什么被折叠?



