Vue技术栈2023-12-20 · 约 6 分钟
Vue3中安装和使用wangEditor最新版本 整合前后端分离上传图片
安装 editor
cmd
npm install @wangeditor/editor --save
具体页面
html
<script setup>
import { onMounted, ref, onBeforeUnmount, shallowRef } from 'vue';
import { baseURL } from "@/constant.js";
//wangediter富文本的依赖
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
// ...
const form = ref({
about: null
});
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef()
const editorConfig = { placeholder: '请输入内容...' }
const toolbarConfig = {
// 排除菜单组,写菜单组 key 的值即可
excludeKeys: [
'group-video'
]
}
const token = JSON.parse(localStorage.getItem('mgr_user')).token;
const mode = ref('default')//default 或 simple
editorConfig.MENU_CONF = {}
editorConfig.MENU_CONF['uploadImage'] = {
fieldName: 'file',
server: baseURL + '/file/upload',
headers: { token: token },
// 单个文件上传成功之后
onSuccess(file, res) {
console.log('上传成功', res)
ElMessage({
message: '上传成功',
type: 'success',
})
},
// 单个文件上传失败
onFailed(file, res) {
console.log('上传失败', res)
ElMessage.error(res.msg)
insertFn(res.data)
},
onError(file, err, res) {
console.log('上传出错', err, res)
ElMessage.error('上传出错')
},
customInsert(res, insertFn) {
// res 即服务端的返回结果
// 从 res 中找到 url alt href ,然后插图图片
insertFn(res.data)
}
}
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const editor = editorRef.value
if (editor == null) return
editor.destroy()
})
// 记录 editor 实例,重要!
const handleCreated = (editor) => {
editorRef.value = editor
}
</script>
<template>
<div style="border: 1px solid #ccc">
<Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
<Editor style="height: 900px; overflow-y: hidden;" v-model="form.about" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
</div>
</template>
觉得有用就点个赞吧