# wangEditor

houdunren.com (opens new window) @ 向军大叔

xj-small

wangEditor (opens new window)是优秀的国产富文本编辑器,下面我们来掌握在项目中集成上这款编辑器。

image-20201120231553289

# 安装

可以使用npm或yarn进行安装

yarn add wangeditor

也可以使用cdn引入,这会减少打包的文件大小

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/wangeditor@latest/dist/wangEditor.min.js"></script>

# VUE组件

下面将wangEditor开发为vue3组件

# TS类型声明

在typeing.d.ts中声明 wangEditor 的TS类型

declare class wangEditor {
  constructor(el: string)
  create: () => void
  txt: { html: Function }
  config: { [key: string]: any }
}

# 定义编辑器类

export default class {
  editor: wangEditor
  constructor(el: string, onChange: Function, public config: { [key: string]: any }) {
    this.editor = new wangEditor(el)
    this.editor.config.height = config.height
    this.editor.config.uploadImgServer = config.uploadImgServer

    this.editor.config.uploadImgHooks = this.uploadImgHooks()
    this.editor.config.onchange = onChange
    this.editor.create()

    this.editor.txt.html(config.modelValue)
  }

  private uploadImgHooks() {
    return {
      customInsert: function (insertImgFn: Function, result: any) {
        // insertImgFn 可把图片插入到编辑器,传入图片 src ,执行函数即可
        insertImgFn(result.result.url)
      },
    }
  }
}

# 组件代码

然后定义wangEditorr的Vue组件

<script setup lang="ts">
import { nextTick } from 'vue';
import wangEditor from './wangEditor'
interface IProps {
	modelValue?: string
	height?: number
	uploadImgServer?: string
}
const props = withDefaults(defineProps<IProps>(), {
	modelValue: '',
	height: 300,
	uploadImgServer: '/api/upload/image'
})

const emit = defineEmits(['update:modelValue'])

nextTick(() => {
	const editor = new wangEditor('#editor', (newHtml: string) => {
		emit('update:modelValue', newHtml)
	}, props)
})
</script>

<template>
	<div id="editor"></div>
</template>

# 使用组件

<script setup lang="ts">
import Editor from '@/components/wang/editor.vue'
import { ref } from 'vue';
const content = ref('abc')
</script>

<template>
	<div class>
		<Editor :config="{ height: 300 }" v-model="content" />
		{{ content }}
	</div>
</template>

下面对props属性进行说明

属性 说明 默认值
v-model 编辑器数据
uploadImgServer 图片上传后台地址
height 编辑器高度

# 后台上传

后台需要返回以下数据结构

data: { url: '图片地址' }