wang-editor.vue 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <template>
  2. <div id="editor">
  3. <div style="border: 1px solid #ccc">
  4. <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
  5. <Editor style="height: 500px; overflow-y: hidden" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
  6. </div>
  7. </div>
  8. </template>
  9. <script lang="ts" setup>
  10. import '@wangeditor/editor/dist/css/style.css'; // 引入 css
  11. import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
  12. import type { Ref } from 'vue';
  13. import { ref, toRefs, onBeforeUnmount, shallowRef, computed } from 'vue';
  14. interface EmitEvent {
  15. (e: 'update:modelValue', params: string): void;
  16. }
  17. // #region 参数传递
  18. const props = defineProps({
  19. modelValue: { type: String, default: () => '' },
  20. mode: { type: String, default: () => 'default' },
  21. url: { type: String, default: () => '' },
  22. });
  23. const { modelValue } = toRefs(props);
  24. const { mode } = toRefs(props);
  25. const { url } = toRefs(props);
  26. // #endregion
  27. const editorRef = shallowRef();
  28. const onCreated = (editor: string) => {
  29. editorRef.value = Object.seal(editor); // 一定要用 Object.seal() ,否则会报错
  30. };
  31. const emit = defineEmits<EmitEvent>();
  32. const valueHtml = computed({
  33. get() {
  34. return modelValue.value;
  35. },
  36. set(value: string) {
  37. emit('update:modelValue', value);
  38. },
  39. });
  40. const customPicInsert = (result: { errcode: number; uri: string; name: string }, insertFn: any) => {
  41. const { errcode, uri, name } = result;
  42. const url = `${import.meta.env.VITE_APP_HOST}${uri}`;
  43. if (errcode === 0) {
  44. insertFn(url, name);
  45. }
  46. };
  47. let editorConfig: Ref<object> = ref({
  48. placeholder: '请输入内容...',
  49. MENU_CONF: { uploadImage: { server: url, customInsert: customPicInsert } },
  50. });
  51. let toolbarConfig: Ref<object> = ref({
  52. // excludeKeys: ['insertImage', 'insertVideo', 'uploadVideo', 'video'],
  53. });
  54. onBeforeUnmount(() => {
  55. const editor = editorRef.value;
  56. if (editor == null) return;
  57. editor.destroy();
  58. });
  59. </script>
  60. <style src="@wangeditor/editor/dist/css/style.css"></style>
  61. <style scoped>
  62. .editor {
  63. overflow-y: hidden;
  64. }
  65. </style>