安装wangeditor

npm install wangeditor@4.6.10

页面中引入使用

import WangEditor from 'wangeditor'
const editor = ref(null)
import { uploadImgServer, getToken } from '@/utils'

<script setup>
	let instance
	const state = reactive({
		token: getToken()
	})
   	onMounted(() => {
      instance = new WangEditor(editor.value)
      instance.config.showLinkImg = false
      instance.config.showLinkImgAlt = false
      instance.config.showLinkImgHref = false
      instance.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
      instance.config.uploadFileName = 'file'
      // 图片上传需添加token到请求头
      instance.config.uploadImgHeaders = {
        token: state.token
      }
      // 图片返回格式不同,需要自定义返回格式
      instance.config.uploadImgHooks = {
        // 图片上传并返回了结果,想要自己把图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式,可使用 customInsert
        customInsert: function(insertImgFn, result) {
          console.log('result', result)
          // result 即服务端返回的接口
          // insertImgFn 可把图片插入到编辑器,传入图片 src ,执行函数即可
          if (result.data && result.data.length) {
            result.data.forEach(item => insertImgFn(item))
          }
        }
      }
      // 图片上传的地址url
      instance.config.uploadImgServer = uploadImgsServer
      Object.assign(instance.config, {
        // 输入内容会触发change事件
        onchange(e) {
          console.log('change', e)
        },
      })
      instance.create()
      
      if (instance) {
            // 模拟异步请求   根据传入的内容初始化富文本的内容
            setTimeout(() => {
            	instance.txt.html(Content)
            }, 1000)
       }
    })
	onBeforeUnmount(() => {
      instance.destroy()
      instance = null
    })
</script>
	
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐