vue中使用百度富文本编辑器

本文详细介绍了如何在Vue项目中集成百度的UEditor富文本编辑器,包括下载、配置、组件化及定制功能的过程。通过具体步骤与代码示例,展示了如何解决跨域图片显示问题,以及如何通过配置实现编辑器功能的个性化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、下载

https://ueditor.baidu.com/website/download.html#ueditor

下载Jsp 版本 UTF-8版 

二、下载完成后将文件放入vue项目中的静态资源文件中

按照自己的实际路径修改ueditor.config.js中的window.UEDITOR_HOME_URL配置,如下图:

在main.js中引用如下

import '../static/ueditor/ueditor.config.js'
import '../static/ueditor/ueditor.all.min.js'
import '../static/ueditor/lang/zh-cn/zh-cn.js'
import '../static/ueditor/ueditor.parse.min.js'

三、编辑器组件

<template>
  <div>
    <!--下面通过传递进来的id完成初始化-->
    <script :id="randomId" type="text/plain"></script>
  </div>
</template>

  <script>
export default {
  name: "UE",
  props: {
    value: {
      default: function() {
        return "";
      }
    },
    //配置可以传递进来
    config: Object
  },
  data() {
    return {
      //每个编辑器生成不同的id,以防止冲突
      randomId: "editor_" + Math.random() * 100000000000000000,
      //编辑器实例
      instance: null,
      ready: false
    };
  },
  watch: {
    value: function(val, oldVal) {
      if (val != null && this.ready) {
        this.instance = UE.getEditor(this.randomId, this.config);
        this.instance.setContent(val);
      }
    }
  },
  //此时--el挂载到实例上去了,可以初始化对应的编辑器了
  mounted() {
    this.initEditor();

  },

  beforeDestroy() {
    // 组件销毁的时候,要销毁 UEditor 实例
    if (this.instance !== null && this.instance.destroy) {
      this.instance.destroy();
    }
  },
  methods: {
    initEditor() {
      const _this = this;
      //dom元素已经挂载上去了
      this.$nextTick(() => {
        this.instance = UE.getEditor(this.randomId, this.config);
        // 绑定事件,当 UEditor 初始化完成后,将编辑器实例通过自定义的 ready 事件交出去
        this.instance.addListener("ready", () => {
          this.ready = true;
          this.$emit("ready", this.instance);
        });
      });
    },
    setText(con) {
      this.instance = UE.getEditor(this.randomId, this.config);
      this.instance.setContent(con);
    },
    getUEContent() {
      // 获取内容方法
      return this.instance.getContent();
    }
  }
};
</script>

<style scoped>
#edui1 {
  width: 100%;
}
</style>

四、调用组件

<template>
  <div class="components-container">
    <button @click="getUEContent()">获取内容</button>
    <button @click="setText()">设置内容</button>
    <div class="editor-container">
      <UE :value="defaultMsg" :config="config" ref="ue"></UE>
    </div>
  </div>
</template>
<style>

</style>
<script>
  import UE from '../../components/ue.vue';
  export default {
    components: {UE},
    data() {
      return {
        defaultMsg: '这里是UE测试',
        config: {
          initialFrameWidth: null,
          initialFrameHeight: 500
        }
      }
    },
    methods: {
      getUEContent() {
        let content = this.$refs.ue.getUEContent();
        console.log(content)
      },
      setText(){
        let content = this.$refs.ue.setText();
      }
    }
  };
</script>

最终效果如图:

五、配置

实例化后的初始编辑器,里面的功能有很多,其中有一部分可能是我们完全用不到的,百度提供了可以定制的功能

有两种方式

初始化时添加配置,如下

<script type="text/javascript">
    //实例化编辑器
    var ue = UE.getEditor('editor', {
    toolbars: [
        [
            'undo', //撤销
            'bold', //加粗
            'underline', //下划线
            'preview', //预览
            'horizontal', //分隔线
            'inserttitle', //插入标题
            'cleardoc', //清空文档
            'fontfamily', //字体
            'fontsize', //字号
            'paragraph', //段落格式
            'simpleupload', //单图上传
            'insertimage', //多图上传
            'attachment', //附件
            'music', //音乐
            'inserttable', //插入表格
            'emotion', //表情
            'insertvideo', //视频
            'justifyleft', //居左对齐
            'justifyright', //居右对齐
            'justifycenter', //居中对
            'justifyjustify', //两端对齐
            'forecolor', //字体颜色
            'fullscreen', //全屏
            'edittip ', //编辑提示
            'customstyle', //自定义标题
            'template', //模板
             ]
        ]
    });
</script>

想定制什么功能,只需要参照上面下载的编辑器demo内的ueditor.config.js文件中toolbars属性,将对应的字符串添加进去即可:

ueditor.config.js文件可以定制编辑器的很多功能,只需要将对应属性前面的'//'去掉,true为开启,false为关闭进行设置即可.比如:

实际应用时我们还有可能在一个域名下上传百度编辑器编辑的内容(例如:在www.52lnamp.com域名下上传了一张图片),而需求不单单是要在这域名下展示,还需要可以在其它域名下展示,这时就会出现图片不存在的情况,

这是因为百度编辑器的配置文件中默认的上传路径是相对路径,也就是说上面上传的图片的地址是相对于当前的域名进行上传的,只有在你上传的域名下可以展示,其它域名是显示不出来的,

如果要在另外一个域名上展示的话只需要修改配置文件为绝对路径就可以了,打开上面下载的demo,找到php/config.json文件,打开后你会看到

其中imageUrlPrefix这个属性加上域名即可:"imageUrlPrefix": "http://www.xxx.com", /* 图片访问路径前缀 */

需要注意的是添加域名的时候必须带上http or https,只有这样写出来的才能正常显示,不加的话在你引用的时候会在前面重复加上一个域名,基本了解了这些足以应对日常的需求,有其它另类的需求可以参考百度编辑器文档

图片上配置参考如下

https://blog.youkuaiyun.com/weixin_42310713/article/details/100113018

### 在 Vue3 中集成和使用百度富文本编辑器 #### 准备工作 为了在 Vue3 项目中成功集成百度 UEditor 富文本编辑器,需先下载并准备 UEditor 的源码[^1]。 #### 引入必要的文件 打开 `/src/main.js` 文件,在适当的位置插入如下代码来配置百度编辑器: ```javascript import '../static/ue/ueditor.config.js' import '../static/ue/ueditor.all.min.js' import '../static/ue/lang/zh-cn/zh-cn.js' import '../static/ue/ueditor.parse.min.js' ``` 这些脚本负责初始化编辑器实例及其所需的语言包和其他资源文件[^3]。 #### 创建组件封装 创建一个新的 Vue 组件用于封装 UEditor 实例。例如 `UEditor.vue`: ```vue <template> <div id="editor"></div> </template> <script setup> import { onMounted } from 'vue'; // 假设已按照上述方法导入了 UE 对象 let editor; onMounted(() => { const ueContainerId = "editor"; editor = window.UE.getEditor(ueContainerId); }); </script> <style scoped> /* 可选样式 */ #editor{ width: 80%; } </style> ``` 此部分利用 Composition API (`setup`) 和生命周期钩子 `onMounted()` 来确保页面加载完成后才启动编辑器实例化过程。 #### 图片上传处理 当涉及到图片粘贴或上传操作时,需要注意设置相应的回调函数以处理图像数据,并最终通过 `insertHtml` 方法将 URL 插入到编辑区域中[^4]: ```javascript const handleImageUpload = (file) => new Promise((resolve, reject) => { // 这里可以加入实际的服务器端接口请求逻辑 let formData = new FormData(); formData.append('image', file); fetch('/api/upload-image', { method: 'POST', body: formData, }) .then(response => response.json()) .then(data => resolve(data.url)) .catch(error => reject(error)); }); editor.addListener('beforeInsertImage', function (_, list){ list.forEach(item=>{ if (!item.src.startsWith('http')){ // 如果是远程链接,则认为是本地上传 handleImageUpload(item).then(url=>Object.assign(item,{ src:url })); } }); }); ``` 这段 JavaScript 代码展示了如何监听 `beforeInsertImage` 事件并对每张待插入的图片执行异步上传动作;一旦获取到了有效的网络地址就更新原对象中的 `src` 属性值。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值