安装:
cnpm i wangeditor@4.7.15 -S
components文件夹下新建一个Vue组件:
<template>
<div>
<div id="websiteEditorElem" style="height:300px;background: #ffffff;"></div>
</div>
</template>
<script>
import { getToken } from "@/utils/auth";
import EWangEditor from "wangeditor";
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
export default {
name: "wangEditor",
props: {
content: "" //获取从父组件中传过来的值,主要用于修改的时候获取值,并加入到富文本框中
},
data() {
return {
phoneEditor: '',
name: '',
}
},
methods: {
},
mounted() {
this.phoneEditor = new EWangEditor('#websiteEditorElem')
// true 文件采用base64保存 false:文件采用地址方式保存
const b = false;
// 图片以base64形式保存
this.phoneEditor.config.debug = true;
if (b) {
this.phoneEditor.config.uploadImgShowBase64 = true
}else{
// 配置上传图片功能
this.phoneEditor.config.uploadImgServer = uploadFileUrl.value //填写后台服务器地址
this.phoneEditor.config.uploadFileName = 'file' // 后端接受上传文件的参数名
this.phoneEditor.config.uploadImgMaxSize = 30 * 1024 * 1024 // 限制上传图片的大小为3MB
this.phoneEditor.config.uploadImgMaxLength = 600 // 限制一次最多上传 6 张图片
this.phoneEditor.config.uploadImgTimeout = 40 * 60 * 1000 // 设置超时时间
this.phoneEditor.config.uploadImgParams = {file_type: 'img'}
this.phoneEditor.config.uploadImgHeaders = {Authorization: "Bearer " + getToken()}
this.phoneEditor.config.uploadImgHooks = {
customInsert: function (insertImg, result, editor) {
if (result.code === 200) {
// 插入图片到编辑器中
insertImg(baseUrl+result.fileName)
} else {
console.error('上传图片失败')
}
}
}
}
this.phoneEditor.config.zIndex = 100;
this.phoneEditor.config.pasteFilterStyle = false;
// 创建一个富文本编辑器
this.phoneEditor.create()
// 修改的时候,需要富文本内容回显,则需要加入以下代码
this.phoneEditor.txt.html(this.modelValue)
this.phoneEditor.config.onchange = (html) => {
this.info_ = html // 绑定当前逐渐地值
this.$emit('change', this.info_) // 将内容同步到父组件中
}
},
}
</script>
父组件引用:
页面:
<el-form-item label="内容">
<WangEdit @change="grtUrl" :content="editForm.content"></WangEdit>
</el-form-item>
JS:
<script>
import WangEdit from '@/components/wangEditor.vue' //WangEditor在项目中的地址
export default{
components:{ WangEdit },
data(){
return{
editForm:{content:''},
}
},
methods:{
grtUrl(path){
this.editForm.content = path;
},
saveOrUpdate(){
console.log('send',this.editForm)
//注释掉的这行代码就是控制页面显示是否带<p>标签的
//this.editForm.content=this.editForm.content.replace(/<[^>]+>/g,"")
//todo 以下可进行后端接口保存调用...
},
}
}
</script>
尾声:
有问题可看视频教学 官方网站