1.安装
yarn add @wangeditor/editor
# 或者 npm install @wangeditor/editor --save
yarn add @wangeditor/editor-for-vue@next
# 或者 npm install @wangeditor/editor-for-vue@next --save
2.使用
封装成组件
<template>
<div style="border: 1px solid #ccc" v-if="innerVisible">
<Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
<Editor
style="height: 500px; overflow-y: hidden"
v-model="description"
@onChange="lisChange($event)"
:defaultConfig="editorConfig"
:mode="mode"
@onCreated="onCreated"
/>
</div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css'
// 模拟vue2中的中央时间总线
import Bus from '@/utils/bus.ts'
import { UserStore } from '@/store'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ref, onBeforeUnmount, onMounted, toRefs, shallowRef } from 'vue'
const props = defineProps({
description: {
type: String,
default: ''
},
innerVisible: {
type: Boolean,
default: false
}
})
// 用于修改父组件传递的属性的值
const emit = defineEmits(['update:description'])
const valueHtml = ref('')
const editorRef = shallowRef()
// const html = ref('<p>hello</p>')
const { description } = toRefs(props)
const toolbarConfig = ref({})
const editorConfig = ref({ MENU_CONF: {}, placeholder: '请输入内容...' })
const userStore = UserStore()
const token = userStore.token
editorConfig.value.MENU_CONF['uploadImage'] = {
// 上传图片的配置
server: window.appsettings.baseUrl_JAVA + '/file/upload',
fieldName: 'file',
timeout: 5 * 1000, // 5s
meta: {},
headers: { Authorization: `Bearer ${token}` },
metaWithUrl: false, // join params to url
maxFileSize: 10 * 1024 * 1024, // 10M
// base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb
customInsert(res, insertFn) {
console.log(res)
if (!res) throw new Error(`Image url is empty`)
const url = window.appsettings.baseUrl_JAVA + '/file/' + res + '/download'
const alt = ''
const href = ''
insertFn(url, alt, href)
}
}
editorConfig.value.MENU_CONF['uploadVideo'] = {
// 上传视频的配置
server: window.appsettings.baseUrl_JAVA + '/file/upload',
timeout: 5 * 1000, // 5s
meta: {},
headers: { Authorization: `Bearer ${token}` },
fieldName: 'file',
metaWithUrl: false, // join params to url
customInsert(res, insertFn) {
const url = window.appsettings.baseUrl_JAVA + '/file/' + res + '/download'
const poster = ''
insertFn(url, poster)
}
}
const mode = ref('default')
const onCreated = editor => {
editorRef.value = Object.seal(editor) // 一定要用 Object.seal() ,否则会报错
}
const lisChange = e => {
valueHtml.value = e.getHtml()
}
onMounted(() => {
// 点击确定后再更改父组件传递过来的属性
Bus.$on('changeHtml', () => {
console.log(valueHtml.value)
// 修改父组件传递的属性的值
emit('update:description', valueHtml.value)
})
}),
onBeforeUnmount(() => {
const Editor = editorRef.value
if (Editor === null) return
Editor.destroy() // 组件销毁时,及时销毁编辑器
})
</script>
<style></style>
富文本插件官网: www.wangeditor.com/v5/for-fram…