在Vue3中使用富文本

1、安装富文本,在这里需要特别注意安装时版本的问题,本人第一次安装没有写版本号,导致报错,降低版本之后,安装成功了

npm i wangeditor@4.6.3

2、新建文件夹,作为富文本的显示区域

<template>
  <div id="editor"></div>
</template>
<script lang="ts">//在这里申明使用ts进行代码的校验
import WangEditor from 'wangeditor';//引入wangeditor文件夹
import { defineComponent, onMounted, PropType, ref, toRefs, watch,onBeforeUnmount } from 'vue';
export default defineComponent({
  emits: ['passContent'],
  props: {
    isClear: {
      type: Boolean as PropType<boolean>
    }
  },
  setup(props, { emit }) {
    let instance: any = '';
    let editorContent = ref<string>('');
    let { isClear } = toRefs(props);
    watch(isClear, (newValue, oldValue) => {
      if (newValue) {
        instance.txt.clear();
        emit('passContent', editorContent.value);
      }
    });
    onMounted(() => {
      instance = new WangEditor('#editor');
      instance.config.height = 300;
      instance.config.showFullScreen = false;
      instance.config.menus = [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'indent',
        'lineHeight',
        'foreColor',
        'list',
        'justify'
      ];
      // 配置 onchange 回调函数
      instance.config.onchange = function (newHtml: string): void {
        editorContent.value = instance.txt.text();
        emit('passContent', editorContent.value);
      };
      instance.config.onchangeTimeout = 1000; // 修改为 500ms
      instance.create();
    });
    // 在页面将要卸载的时候,销毁我们创建的实例
    onBeforeUnmount(() => {
      instance.destroy();
      instance = null;
    })
    return {
      instance,
      isClear
    };
  }
});
</script>

3、在父组件中的使用

<template>
  <el-dialog v-model="dialog" :title="title" width="50%" :before-close="close">
    <div class="editor-area">
      <el-form
        label-width="60px"
        :rules="rules"
        :model="formLine"
        ref="formRef"
      >
        <el-form-item label="标题:" prop="title">
          <el-input v-model="formLine.title"></el-input>
        </el-form-item>
        <el-form-item label="内容:" prop="content">
          <Editor
            v-model:isClear="isClear"
            @passContent="passContent"
            :detailContent="detailContent"
          ></Editor>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button @click="release" type="primary" v-loading="loading"
          >发布</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import Editor from './editor.vue';
import api from '@/assets/api';
import { ElMessage } from 'element-plus';
import {
  computed,
  defineComponent,
  PropType,
  toRefs,
  Ref,
  reactive,
  ref,
  watch
} from 'vue';
export default defineComponent({
  emits: ['updateBoardList'],
  components: { Editor },
  props: {
    isShowAdd: {
      type: Boolean as PropType<boolean>,
      required: true
    },
    title: {
      type: String as PropType<string>,
      required: true
    },
    editorId: {
      type: String as PropType<string>,
      required: true
    }
  },
  setup(props, context: any) {
    const { isShowAdd, title, editorId } = toRefs(props);
    const inputContent = ref<string>('');
    const isClear = ref<boolean>(false);
    const loading = ref<boolean>(false);
    let detailContent = ref<string>('');
    const formRef = ref();
    const formLine = reactive({
      title: ''
    });
    // 发布
    const release = async () => {
      isClear.value = false;
      loading.value = true;
      if (title.value === '新增公告') {
        const data = {
          content: inputContent.value,
          title: formLine.title
        };
        const res = await api.boardManage.boarAdd(data);
        if (res.code === api.code.SUCCESS) {
          ElMessage({
            message: '新增公告成功',
            type: 'success'
          });
          context.emit('updateBoardList');
          close();
        }
      } else {
        const data = {
          content: inputContent.value,
          title: formLine.title,
          id: editorId.value
        };
        const res = await api.boardManage.editorBoard(data);
        if (res.code === api.code.SUCCESS) {
          ElMessage({
            message: '编辑公告成功',
            type: 'success'
          });
          context.emit('updateBoardList');
          close();
        }
      }
      loading.value = false;
    };
    const passContent = (value: string): void => {
      inputContent.value = value;
    };
    const { dialog, close } = useHandleDialog(
      isShowAdd,
      context.emit,
      isClear,
      formRef,
      detailContent
    );
    const { rules } = useRoles();
    watch(isShowAdd, async newValue => {
      if (newValue) {
        isClear.value = false;
        // 详情信息
        if (title.value === '编辑公告') {
          let params = {
            id: editorId.value
          };
          const res = await api.boardManage.detail(params);
          if (res.code === api.code.SUCCESS) {
            formLine.title = res.data.title;
            detailContent.value = res.data.content;
          }
        }
      } else {
        isClear.value = true;
      }
    });
    return {
      dialog,
      close,
      rules,
      formLine,
      release,
      title,
      inputContent,
      passContent,
      isClear,
      formRef,
      loading,
      detailContent
    };
  }
});

// 弹窗
const useHandleDialog = (
  visible: Ref<boolean>,
  emit: Function,
  isClear: Ref<boolean>,
  formRef: any,
  detailContent:Ref<string>
) => {
  const dialog = computed(() => {
    return visible.value;
  });
  const close = () => {
    emit('update:isShowAdd', false);
    isClear.value = true;
    formRef.value.resetFields();
    formRef.value.clearValidate('content');
    detailContent.value = '';
  };
  return {
    dialog,
    close
  };
};

// 表单验证
const useRoles = () => {
  const rules = {
    title: {
      required: true,
      message: '请输入标题',
      trigger: 'blur'
    },
    content: {
      required: true,
      message: '请输入内容',
      trigger: 'blur'
    }
  };
  return {
    rules
  };
};
</script>
<style lang="scss" scoped>
.el-dialog {
  .el-form-item--mini:nth-child(2) .el-form-item__content {
    height: 300px;
  }
}
.editor-area {
  padding: 0 0.4rem;
}
</style>

以上代码粘贴、赋值即可使用,一些其它的功能配置可以参考:https://www.wangeditor.com/doc/#demo官网

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐