vue 安装 npm i wangeditor --save
创建一个editoritem组件
components/editoritem.vue //目录以自己项目为主
<template lang="html">
<div class="editor">
<div ref="toolbarContainer" class="toolbar" id="toolbar-container">
</div>
<div ref="textContainer" class="text" id="text-container">
</div>
</div>
</template>
<script>
import E from 'wangeditor'
export default {
name: 'editoritem',
data () {
return {
editor: null,
info_: null
}
},
model: {
prop: 'value',
event: 'change'
},
props: {
value: {
type: String,
default: ''
},
isClear: {
type: Boolean,
default: false
}
},
watch: {
isClear (val) {
if (val) {
this.editor.txt.clear()
this.info_ = null
}
},
value: function (value) {
if (value !== this.editor.txt.html()) {
this.editor.txt.html(this.value)
}
}
},
mounted () {
this.seteditor()
this.editor.txt.html(this.value)
},
beforeDestroy () {
// 调用销毁 API 对当前编辑器实例进行销毁
this.editor.destroy()
this.editor = null
},
methods: {
seteditor () {
var vm = this<br> //使用id和ref都可以
//const editor = new E('#toolbar-container', '#text-container')
const editor = new E(vm.$refs.toolbar, vm.$refs.editor)<br>
var getTokenServer = vm.$store.getters.getTokenServer
var getToken = vm.$store.getters.getToken<br>
editor.config.uploadImgShowBase64 = false // base 64 存储图片
editor.config.uploadImgServer = ''// 服务器端地址
editor.config.uploadImgHeaders = {}// 自定义 header
editor.config.uploadFileName = 'file' // 后端接受上传文件的参数名
editor.config.uploadImgMaxSize = 2 * 1024 * 1024 // 将图片大小限制为 2M
editor.config.uploadImgMaxLength = 6
editor.config.uploadImgTimeout = 3 * 60 * 1000 // 设置超时时间
<br> //你想要携带的其他参数
editor.config.uploadImgParams = {
token: getToken,
tokenServer: getTokenServer,
}
editor.config.uploadImgHooks = {
fail: (xhr, editor, result) => {
// 插入图片失败回调
},
success: (xhr, editor, result) => {
// 图片上传成功回调
},
timeout: (xhr, editor) => {
// 网络超时的回调
},
error: (xhr, editor) => {
// 图片上传错误的回调
},
customInsert: (insertImg, result, editor) => {
// 图片上传成功,插入图片的回调
//result为上传图片成功的时候返回的数据,根据自己后台返回的数据格式来取值
let url = "" + result.filename
insertImg(url)
}
}
editor.config.onchange = (html) => {
this.info_ = html
this.$emit('change', this.info_) // 将内容同步到父组件中
}
// 创建富文本编辑器
editor.create()
this.editor = editor
}
}
}
</script>
<style lang="css">
.editor {
width: 100%;
margin: 0 auto;
position: relative;
z-index: 0;
}
.toolbar {
border: 1px solid #ccc;
}
.text {
border: 1px solid #ccc;
min-height: 500px;
}
</style>
父组件中引用:
<template>
<div>
<editor-bar v-model="data"
:isClear="isClear"
@change="change"></editor-bar>
</div>
</template>
<script>
import EditorBar from '../../components/editorItem/editorItem'
export default {
components: {
EditorBar
},
data () {
return {
data: ""
}
},
methods: {
change (val) {
console.log(val)
},
}
}
</script>
<style>
</style>
需要其他配置参见官方文档 http://www.wangeditor.com/