作为一个菜鸟表示真的很难吖。
这个插件就一个字:小巧!好用!
首先我是Vue+springboot的前后端分离
所以在查的时候结合文档和网上的一些例子,在此感谢帮助到我的大佬们!
因为富文本编辑框之后会在很多地方用到,所以我采用了把WangEditor单独拎出来做一个组件然后用父子模块通信的方式来实现富文本的编辑。
项目的文件结构如图:
然后这个WangEditor.vue可以把它理解成子模块,在新闻添加的vue文件
NewsAdd.vue里引入使用这个子模块,故NewsAdd.vue理解为父模块
下面是WangEditor.vue 源码
<template>
<div>
<div ref="editor" style="text-align:left"></div>
<button v-on:click="getContent">查看内容</button>
</div>
</template>
<script>
import E from 'wangeditor'
export default {
name: "WangEditor",
data() {
return {
// 真正的编辑器里的内容
editorContent: '',
// 编辑器对象
editor: null
}
},
watch: {
// watch 表示监听 当父组件的内容变化时需要更新编辑器的内容
content() {
this.editor.txt.html(this.content)
}
},
/**
* 这里使用了 Vue 的 mounted 函数钩子,这属于 Vue 生命周期的一个阶段
*/
mounted() {
var editor = new E(this.$refs.editor)
// 当编辑器内容变化的时候通知父组件
editor.customConfig.onchange = (html) => {
this.editorContent = html
// 通知父级控件方法,富组件可以通过 editorContent 事件去获取最新的编辑器内容
this.$emit('editorContent', html)
}
// 下面两个配置,使用其中一个即可显示“上传图片”的tab。但是两者不要同时使用!!!
// editor.customConfig.uploadImgShowBase64 = true // 使用 base64 保存图片
editor.customConfig.uploadImgServer = 'http://localhost:8081/uploadImg' // 上传图片到服务器
//图片的大小和数量都是用默认值 5M和1000张
// 将图片大小限制为 3M
// editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024
// 限制一次最多上传 5 张图片
// editor.customConfig.uploadImgMaxLength = 5
//上传图片时,可自定义filename,即在使用formdata.append(name, file)添加图片文件时,自定义第一个参数。
editor.customConfig.uploadFileName = 'myFileName'
//可使用监听函数在上传图片的不同阶段做相应处理
editor.customConfig.uploadImgHooks = {
// 图片上传并返回结果,图片插入成功之后触发
// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
success: function (xhr, editor, result) {
},
customInsert: function (insertImg, result, editor) {
var url =result.data;//获取后台返回的url
insertImg(url);
}
}
editor.create()
editor.txt.html(this.content)
},
props: {
// 传递过来的编辑器内容参数,用于设置编辑器内容
content: {
type: String,
default: ''
}