vue3 +TS 富文本框引入使用(vditor,tinymce)

目录

一.vditor 初步安装使用

1.安装下载依赖

2.创建组件

3.引用

4.具体目录实践

二.Tinymce 初步创建使用

 1.安装下载依赖

2.创建组件

3.引用

4.具体目录实践


一.vditor 初步安装使用

1.安装下载依赖

npm install vditor --save

 具体参考配置

2.创建组件

具体路径在src/components/ 下

<template>
  <div ref="vditorContainerRef"></div>
  <el-button type="primary" @click="getContent">获取内容</el-button>
</template>

<script setup lang="ts">
// @ts-ignore
import Vditor from 'vditor';
import { onMounted, ref } from 'vue';
import 'vditor/dist/index.css';

const vditorContainerRef = ref(null);
let vditor:any;

const init=()=>{
   vditor = new Vditor(vditorContainerRef.value, {
    height: 650,
    mode: "wysiwyg", // 显示预览内容
    placeholder: "请输入内容...",
    toolbarConfig: {
      pin: true
    },
    cache: {
      enable: false
    },
    after: () => {
      // contentEditor.value.setValue("");
    },
    // 其他 Vditor 配置选项
    upload: {
    url: 'url', // sm.ms 图床的上传接口地址
    accept: 'image/*', // 限制上传的文件类型为图片
    withCredentials: true, // 不携带跨域请求的凭据
    headers: {},
    // 自定义上传成功的回调函数
    success: (editor: { insertValue: (arg0: string) => void; }, msg: string) => {
      const data = JSON.parse(msg);
      if (data.code === 'success') {
        // 上传成功,将图片插入到编辑器中
        editor.insertValue(`![${data.data.filename}](${data.data.url})`);
      } else {
        console.error('上传失败1:', data.message);
      }
    },
    // 自定义上传失败的回调函数
    error: (msg: any) => {
      console.error('上传失败2:', msg);
    },
  },
  });
  console.log(vditor);

}

const getContent = () => {
  if (vditor) {
    const content = vditor.getValue();
    console.log('获取到的内容:', content);
  } else {
    console.error('Vditor 实例尚未初始化');
  }
}

onMounted(() => {
  init()
});

</script>

<style scoped></style>

3.引用

<template>
  <div>
    <Vditor></Vditor>

    <!-- <Tinymce3 ></Tinymce3> -->
  </div>
</template>

<script setup lang="ts">
import Vditor from "@/components/vditor.vue"

// import Tinymce2 from "@/components/tinymce_vue2.vue" //vue2 写法
// import Tinymce3 from "@/components/tinymce_vue3.vue"

</script>

<style scoped></style>

二.Tinymce 初步创建使用

 1.安装下载依赖

npm install tinymce -S

npm install @tinymce/tinymce-vue -S

具体参考配置

2.创建组件

 具体路径在src/components/ 下

<template>
  <div class="tinymce-boxz">
    <Editor v-model="content" :api-key="apiKey" :init="init" />
  <el-button type="primary" @click="getContent">获取内容</el-button>

  </div>
</template>

<script setup lang="ts">
import Editor from "@tinymce/tinymce-vue";
import { reactive, ref, toRefs } from "@vue/reactivity";

const content = ref("默认文字 hello word");

const tiny = reactive({
  apiKey: "qjdvms0zngrhubafzr183whhbxhou97b57b9yrg3wrv42zp8", //https://github.com/tinymce/tinymce-vue/blob/main/src/demo/views/Iframe.vue
  init: {
    language: "zh_CN", //语言类型
    placeholder: "在这里输入文字", //textarea中的提示信息
    min_width: 320,
    min_height: 220,
    height: 500, //注:引入autoresize插件时,此属性失效
    resize: "both", //编辑器宽高是否可变,false-否,true-高可变,'both'-宽高均可,注意引号
    branding: false, //tiny技术支持信息是否显示
    // statusbar: false,  //最下方的元素路径和字数统计那一栏是否显示
    // elementpath: false, //元素路径是否显示

    font_formats:
      "微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;", //字体样式
    plugins:
      "print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern autosave emoticons", //插件配置 axupimgs indent2em
    toolbar: [
      "fullscreen undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | bullist numlist | blockquote subscript superscript removeformat ",
      "styleselect formatselect fontselect fontsizeselect |  table image axupimgs media emoticons charmap hr pagebreak insertdatetime  selectall visualblocks searchreplace | code print preview | indent2em lineheight formatpainter",
    ], //工具栏配置,设为false则隐藏
    // menubar: "file edit my1", //菜单栏配置,设为false则隐藏,不配置则默认显示全部菜单,也可自定义配置--查看 http://tinymce.ax-z.cn/configure/editor-appearance.php --搜索“自定义菜单”

    // images_upload_url: '/apib/api-upload/uploadimg',  //后端处理程序的url,建议直接自定义上传函数image_upload_handler,这个就可以不用了
    // images_upload_base_path: '/demo',  //相对基本路径--关于图片上传建议查看--http://tinymce.ax-z.cn/general/upload-images.php
    paste_data_images: true, //图片是否可粘贴
    //此处为图片上传处理函数
    images_upload_handler: (blobInfo: { blob: () => Blob; }, success: (arg0: string | ArrayBuffer | null) => void, failure: any) => {
      // 这里用base64的图片形式上传图片,
      let reader = new FileReader(); //本地预览
      reader.readAsDataURL(blobInfo.blob());
      reader.onloadend = function () {
        const imgbase64 = reader.result;
        success(imgbase64);
      };
    },

    file_picker_types: "file image media", //file image media分别对应三个类型文件的上传:link插件,image和axupimgs插件,media插件。想屏蔽某个插件的上传就去掉对应的参数
    // 文件上传处理函数
    file_picker_callback: function (callback: (arg0: any, arg1: { title: string; }) => void, value: any, meta: { filetype: string; }) {
      // 使用案例http://tinymce.ax-z.cn/general/upload-images.php
      // meta.filetype  //根据这个判断点击的是什么file image media

      let filetype; //限制文件的上传类型,需要什么就添加什么的后缀
      if (meta.filetype == "image") {
        filetype = ".jpg, .jpeg, .png, .gif, .ico, .svg";
      } else if (meta.filetype == "media") {
        filetype = ".mp3, .mp4, .avi, .mov";
      } else {
        filetype =
          ".pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4, .jpg, .jpeg, .png, .gif, .ico, .svg";
      }
      let inputElem = document.createElement("input"); //创建文件选择
      inputElem.setAttribute("type", "file");
      inputElem.setAttribute("accept", filetype);
      inputElem.click();
      inputElem.onchange = () => {
        let file: any;

        if (inputElem.files) {
          // 在这里安全地使用 fileInput.files
          file = inputElem.files[0]; //获取文件信息
          // 进行其他操作
        } else {
          console.error('没有选择文件');
        }

        // 所有都转成base64文件流,来自官方文档https://www.tiny.cloud/docs/configure/file-image-upload/#file_picker_callback
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
          // Note: Now we need to register the blob in TinyMCEs image blob
          // registry. In the next release this part hopefully won't be
          // necessary, as we are looking to handle it internally.
          let id = "blobid" + new Date().getTime();
          let blobCache = tinymce.activeEditor.editorUpload.blobCache;

          let base64;

          if (reader.result instanceof ArrayBuffer) {
            // 将 ArrayBuffer 转换为字符串
            const textDecoder = new TextDecoder('utf-8');
            const base64String = textDecoder.decode(reader.result);

            // 使用 split 方法获取 base64 部分
            base64 = base64String.split(',')[1];

            // 在这里使用 base64 变量
            console.log(base64);
          } else {
            console.error('读取文件时发生错误');
          }


          let blobInfo = blobCache.create(id, file, base64);
          blobCache.add(blobInfo);

          // call the callback and populate the Title field with the file name
          callback(blobInfo.blobUri(), { title: file.name });
        };
      };
    },
  },
});

const { apiKey, init } = toRefs(tiny)

const getContent = () => {
  if (content.value) {
    console.log('获取到的内容:', content.value);
  } else {
    console.error('Vditor 实例尚未初始化');
  }
}

</script>
<style scoped>
.tinymce-boxz>textarea {
  display: none;
}
</style>
<style>
/* 隐藏apikey没有绑定当前域名的提示 */
.tox-notifications-container .tox-notification--warning {
  display: none !important;
}

.tox.tox-tinymce {
  max-width: 100%;
}
</style>

3.引用

<template>
  <!-- <Vditor></Vditor> -->

  <Tinymce3 ></Tinymce3>
</template>

<script setup lang="ts">
// import Vditor from "@/components/vditor.vue"

// import Tinymce2 from "@/components/tinymce_vue2.vue" //vue2 写法
import Tinymce3 from "@/components/tinymce_vue3.vue"

</script>

<style scoped></style>

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿online

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值