vue2 wangeditor封装
怎么使用 v-model
子组件 $attrs @input
调用组件:
<WangEditor v-model="form.desc"></WangEditor>
封装组件:
<div style="border: 1px solid #ccc;">
<Toolbar/>
<Editor
v-bind="$attrs"
@onChange="handleChange"
/>
</div>
handleChange(editor) {
this.$emit('input',editor.getHtml())
},
详情:
<template>
<div style="border: 1px solid #ccc;">
<Toolbar
style="border-bottom: 1px solid #ccc"
:editor="editor"
:defaultConfig="toolbarConfig"
:mode="mode"
/>
<Editor
style="height: 500px; overflow-y: hidden;"
v-bind="$attrs"
:defaultConfig="editorConfig"
:mode="mode"
@onCreated="onCreated"
@onChange="handleChange"
/>
</div>
</template>
<script>
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { base } from "@/libs/axios";
export default {
components: {
Editor,
Toolbar,
},
props: {
mode: {
type: String,
default: 'default',
// default: 'simple',
},
configs: {
type: Object,
default: () => ({
toolbar: {},
editor: {},
}),
},
},
data() {
return {
editor: null,
jsonContent: [
{
type: 'paragraph',
lineHeight: '1.5',
children: [
{ text: '', fontFamily: '黑体', fontSize: '16px' }
]
},
]
}
},
computed: {
uploadImageConfig() {
return {
server: base + this.$config.uploadUrl,
fieldName: 'file',
headers: {
token: JSON.parse(window.localStorage.getItem("myData")).token,
},
withCredentials: true,
customInsert: (res, insertFn) => {
const url = `${this.$config.fileUrl()}${res.data.resUrl}`
console.log('customInsert.url', url)
insertFn(url, '', '')
},
//30s
timeout: 30 * 1000,
// maxFileSize: 10 * 1024 * 1024, // 10M
// 上传错误,或者触发 timeout 超时
onError(file, err, res) {
console.log(`${file.name} 上传出错`, err, res)
ElMessage.error(`${file.name}上传出错, 图片大小超出2MB或超时`)
},
}
},
uploadVideoConfig() {
return {
server: base + this.$config.uploadUrl,
fieldName: 'file',
headers: {
token: JSON.parse(window.localStorage.getItem("myData")).token,
},
withCredentials: true,
customInsert: (res, insertFn) => {
console.log(res);
const url = `${this.$config.fileUrl()}${res.data.resUrl}`
console.log('customInsert.url', url)
insertFn(url, '', '')
},
//60s
timeout: 60 * 1000,
onError(file, err, res) {
console.log(`${file.name} 上传出错`, err, res)
ElMessage.error(`${file.name}上传出错, 视频大小超出10MB或超时`)
},
}
},
toolbarConfig() {
return {
...this.configs.toolbar,
}
},
editorConfig() {
return {
placeholder: '请填写内容',
...this.configs.editor,
MENU_CONF: {
uploadImage: this.uploadImageConfig,
uploadVideo: this.uploadVideoConfig,
},
}
},
},
beforeUnmount() {
if (this.editor == null) return
this.editor.destroy()
},
methods: {
handleChange(editor) {
this.$emit('input',editor.getHtml())
},
async onCreated(ref) {
this.editor = Object.seal(ref)
},
},
}
</script>
<style lang="less">
.editor {
border: 1px solid #ccc;
}
</style>