Newer
Older
Nanping_sponge_HHDP / src / components / WangEditor / index.vue
@liyingjing liyingjing on 25 Oct 2 KB 海绵大屏
<template>
  <div style="border: 1px solid #ccc">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { sysUpload } from '@/api/login.js';

const props = defineProps({
  modelValue: [String],
});

const emit = defineEmits();
const { proxy } = getCurrentInstance();
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref('');
const mode = ref('default');
const toolbarConfig = ref({});
const editorConfig = ref({
  placeholder: '请输入内容...',
  MENU_CONF: {},
});

// 富文本上传图片
editorConfig.value.MENU_CONF['uploadImage'] = {
  // 自定义上传图片方法
  customUpload(file, insertFn) {
    proxy.$modal.loading('正在上传中...');
    let formdata = new FormData();
    formdata.append('file', file);
    let config = {
      headers: { 'Content-Type': 'multipart/form-data' },
    };
    sysUpload(formdata, config).then(res => {
      if (res && res.code === 200) {
        // 富文本中插入图片
        insertFn(res.data.url);
      }
      proxy.$modal.closeLoading();
    });
  },
};
// 富文本上传视频
editorConfig.value.MENU_CONF['uploadVideo'] = {
  // 自定义上传方法
  customUpload(file, insertFn) {
    proxy.$modal.loading('正在上传中...');
    let formdata = new FormData();
    formdata.append('file', file);
    let config = {
      headers: { 'Content-Type': 'multipart/form-data' },
    };
    sysUpload(formdata, config).then(res => {
      if (res && res.code === 200) {
        // 富文本中插入图片
        insertFn(res.data.url);
      }
      proxy.$modal.closeLoading();
    });
  },
};

// 编辑器回调函数
const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例,重要!
};

//输入改变
const handleChange = editor => {
  emit('update:modelValue', editor.getHtml());
};

watch(
  () => props.modelValue,
  val => {
    if (!!!val) return;
    console.log('富文本编辑器默认显示内容--', val);
    valueHtml.value = val;
  },
  { immediate: true, deep: true }
);
// 模拟 ajax 异步获取内容
onMounted(() => {});
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>