1.下载富文本插件npm install wangeditor --save
2.写公用组件Editor.vue
<!--
* @Description:
* @Version: 1.0
* @Author: zengxianghui
* @Date: 2022-06-01 14:31:46
* @LastEditors: sunye
* @LastEditTime: 2022-06-22 09:42:53
-->
<template>
<div class="home">
<div id="richText" style="height: 400px; background-color: #fff"></div>
<slot name="text" />
</div>
</template>
<script lang="ts" setup>
import { ref, onMounted, nextTick, watch } from "vue"
import { uploadFile } from "/@/api/message"
import { any } from "vue-types"
import E from "wangeditor"
import { ElMessage } from "element-plus"
//父组件传入值(编辑反显使用)
const props = defineProps({
editorValue: {
type: String,
default: ""
}
})
const emit = defineEmits(["getMsg"])
const phoneEditor = ref("")
onMounted(() => {
seteditor()
phoneEditor.value.txt.html(props.editorValue)
})
watch(
() => props.editorValue,
(newValue, oldValue) => {
// 富文本内容
if (newValue !== phoneEditor.value.txt.html()) {
//防止光标换行乱跳
phoneEditor.value.txt.html(newValue)
}
}
)
const seteditor = () => {
phoneEditor.value = new E("#richText")
if (phoneEditor.value != null) {
phoneEditor.value.destroy() //判断编辑器是否被创建,如果创建了就先销毁。
}
// 上传图片到服务器,base64形式
phoneEditor.value.config.uploadImgShowBase64 = true
// 隐藏网络图片
phoneEditor.value.config.showLinkImg = false
// 创建一个富文本编辑器
phoneEditor.value.create()
phoneEditor.value.config.uploadImgMaxSize = 10 * 1024 * 1024 //限制图片大小
phoneEditor.value.config.onchange = html => {
//富文本信息传给父组件
emit("getMsg", html)
}
phoneEditor.value.config.customUploadImg = (files, insert) => {
// 富文本里的上传图片
const param = new FormData()
param.append("photos", files[0])
let reader = new FileReader()
reader.readAsDataURL(files[0])
reader.onload = function (e) {
let img = new Image()
img.src = e.target.result //获取编码后的值
img.onload = function () {
// 限制图片宽度
if (img.width >= 800 && img.width <= 1200) {
uploadFile("upload", param).then(res => {
// 上传图片接口
if (res.data) {
console.log(res)
insert(res.data.domainName + res.data.uris[0])
}
})
} else {
return ElMessage.error("上传图片宽度在800-1200之间")
}
}
}
}
}
</script>
<style scoped></style>
父组件使用
//import引入组件
<el-form-item label="图片上传" prop="chart">
<UploadImg
:imgWidth="bannerState.imgWidth"
:imgHeight="bannerState.imgHeight"
@getImg="getImg"
:validateImgSize="true"
:fullUrl="bannerState.form.chart"
/>
</el-form-item>