- 首先封装一个简单的wangEditor组件
内容如下:
<template>
<div class="wrapper">
<div ref="editor"></div>
</div>
</template>
<script type="text/ecmascript-6">
import Wangeditor from 'wangeditor'
import { getAppConfig } from '@/utils/config.js'
import axios from 'axios'
const appConfig = getAppConfig()
export default {
components: {},
props: {
defaultMsg: String
},
data() {
return {
editor: null,
editorVal: ''
}
},
watch: {
defaultMsg() {
console.log('defaultMsg:', this.defaultMsg)
this.editor.txt.html(this.defaultMsg)
},
//为了解决实时显示编辑器内容
editorVal() {
this.$emit('getEditorHtml', this.editorVal)
}
},
computed: {},
methods: {
getContain() {
return this.editor.txt.html()
}
},
created() {},
mounted() {
const editor = new Wangeditor(this.$refs.editor)
editor.config.menus = [
'head',
'bold',
'fontSize',
'fontName',
'italic',
'underline',
'strikeThrough',
'indent',
'lineHeight',
'foreColor',
'backColor',
'link',
'list',
'todo',
'justify',
'quote',
'emoticon',
'image',
'video',
// 'table',
// 'code',
'splitLine',
'undo',
'redo'
]
// 配置 onchange 回调函数
editor.config.onchange = newHtml => {
console.log('change 之后最新的 html', newHtml)
//为了解决实时显示编辑器内容
console.log('this', this)
this.editorVal = newHtml
}
editor.config.customUploadImg = function (resultFiles, insertImgFn) {
var forms = new FormData()
forms.append('upfile', resultFiles[0])
axios({
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
url: appConfig.baseUrl + '/coroutine/picture/file/upload',
withCredentials: true,
data: forms
}).then(res => {
if (res.data.status) {
insertImgFn(res.data.data.cloudDomain + '/' + res.data.data.image_path)
} else {
this.$message.error(res.data.message)
}
})
}
editor.config.zIndex = 500
editor.create()
this.editor = editor
}
}
</script>
<style lang="" scoped>
</style>
- 父组件调用
<ueditor @getEditorHtml="getEditorHtml" :defaultMsg="form.configContent" ref="ueditor"></ueditor>
- 需求: 项目需求要求页面左边要展示右边一个富文本编辑器中的内容。
- 问题:
- vue项目数据双向绑定很好实现,问题是怎么获取编辑器中的内容(项目中用的wangEditor),后查看文档(https://www.wangeditor.com/doc/pages/04-%E5%9B%9E%E8%B0%83%E5%87%BD%E6%95%B0/01-onchange%E5%92%8ConSelectionChange.html)配置change事件,获取编辑器中动态内容,通过vue的$emit方法触发父组件中方法并将变化的值传给父组件。
- 其中遇到在config配置方法中调用this一直是undefined的问题,原因是 普通函数与箭头函数this指向的原因,改成箭头函数后,问题解决。
好记性不如烂笔头,一些简单的问题总是会干扰自己,做下笔记。