vue3 項目中需要使用富文本編譯器 支持圖片上傳等 我這里選擇WangEditor
示例如下
父組件
<template> <editer @updateContent="updateContent1" ></editer> </template>
<script setup> import editer from '@/views/test/component/editer1.vue' //引入封裝富文本組件 const data = reactive({ subject: { t1: `題目一` }); const { subject } = toRefs(data);
function updateContent1(e){
subject.value.t1=e;
};
子組件 富文本組件
主要是紅色字部分在這里觸發子組件向父組件傳遞數據
<template> <div ref='editor'> <div :innerHTML='Content'></div> </div> <!-- <button @click='syncHTML'>同步內容</button> --> </template> <script> import { onMounted, onBeforeUnmount, ref, reactive } from 'vue'; import WangEditor from 'wangeditor'; import { getToken } from '@/utils/auth' export default { name: 'app', setup(props,{emit}) { const syncHTML = () => { // console.log("獲取的值",instance.txt.html()) }; const editor = ref(); let instance; onMounted(() => { instance = new WangEditor(editor.value); Object.assign(instance.config, { onchange() { emit("update",instance.txt.html()) }, }); instance.config.showLinkImg = false instance.config.showLinkImgAlt = false instance.config.showLinkImgHref = false instance.config.uploadImgMaxSize = 5 * 1024 * 1024 // 2M instance.config.uploadImgMaxLength = 1 instance.config.uploadFileName = 'avatarfile' instance.config.uploadImgHeaders = { Authorization: getToken() // 上傳接口所需token } // 圖片返回格式不同,這里需要根據后端提供的接口進行調整 instance.config.uploadImgHooks = { // 圖片上傳並返回了結果,想要自己把圖片插入到編輯器中 // 例如服務器端返回的不是 { errno: 0, data: [...] } 這種格式,可使用 customInsert customInsert: function(insertImgFn, result) { console.log('result', result) // result 即服務端返回的接口 // insertImgFn 可把圖片插入到編輯器,傳入圖片 src ,執行函數即可 if (result && result.code === 200) { console.log(result.imgUrl) // 單圖時 insertImgFn函數接收的是返回圖片的全地址,eg:http://img.xxx.com/image/20211025/96759ce5aab246e6860f72a364e4142a.jpg insertImgFn( import.meta.env.VITE_APP_BASE_API + result.imgUrl) // 多圖時,循環調用insertImgFn // result.result.forEach(item => insertImgFn(import.meta.env.VITE_APP_BASE_API+item.url)) } } } // 你自己上傳圖片的接口地址 instance.config.uploadImgServer = import.meta.env.VITE_APP_BASE_API + '/system/user/profile/avatar' instance.create(); }); onBeforeUnmount(() => { console.log("銷毀了") instance.destroy(); instance = null; }); return { syncHTML, editor, }; }, }; </script>
參考 https://blog.csdn.net/weixin_45803990/article/details/118695828