欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Vue2.0中集成UEditor富文本编辑器的方法

程序员文章站 2023-10-18 09:41:21
在vue的'项目中遇到了需要使用富文本编辑器的需求,在github上看了很多vue封装的editor插件,很多对图片上传和视频上传的支持并不是很好,最终还是决定使用uedi...

在vue的'项目中遇到了需要使用富文本编辑器的需求,在github上看了很多vue封装的editor插件,很多对图片上传和视频上传的支持并不是很好,最终还是决定使用ueditor。

这类的文章网上有很多,我进行了摸索、手写代码、汇总、排版,形成了这篇文章。

下载对应的ueditor源码

首先,去官网上下载ueditor的源码,根据你后台语言的不同下载对应的版本(php、asp、.net、jsp)。

下载之后,把资源放到 /static/ue/ 静态目录下。文档结构如下:

Vue2.0中集成UEditor富文本编辑器的方法

(我把ueditor放到了static静态目录下面,这里的文件不会被webpack打包,当然你也可以选择性地放进src中)

编辑 ueditor 编辑器 配置文件

我们打开 ueditor.config.js,修改其中的window.ueditor_home_ur配置,如下:

window.ueditor_home_url = "/static/ue/";   //指定编辑器资源文件根目录
var url = window.ueditor_home_url || getuebasepath();
ueditor.config.js文件有很多配置,可以在这里进行一些初始化的全局配置,比如编辑器的默认宽高等:
,initialframewidth:1000 //初始化编辑器宽度,默认1000
,initialframeheight:320 //初始化编辑器高度,默认320
其他的参数配置,在该文件中有详细列出,或者参考官方文档

将编辑器集成到系统中

打开 /src/main.js 文件,插入下面的代码:

//ueditor
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'

开发公共组件 ue.vue

我们在 /src/components/ 目录下创建 ue.vue文件,作为我们的编辑器组件文件。

下面代码提供简单功能,具体使用根据需求完善该组件即可。

<template>
  <div>
    <script type="text/plain"></script>
  </div>
</template>
<script>
  export default {
    name: 'ue',
    data () {
      return {
        editor: null
      }
    },
    props: {
      value: '',
      config: {}
    },
    mounted () {
      this.editor = window.ue.geteditor('editor', this.config);
      this.editor.addlistener('ready', () => {
        this.editor.setcontent(this.value)
      })
    },
    methods: {
      getuecontent () {
        return this.editor.getcontent()
      }
    },
    destroyed () {
      this.editor.destroy()
    }
  }
</script>

组件暴露了两个接口:

  • value是编辑器的文字
  • config是编辑器的配置参数

在其他页面中使用该组件

简单地创建一个需要ueditor的页面,再该页面中使用刚才封装好的ue.vue组件:

<template>
  <div>
    <uediter :value="ueditor.value" :config="ueditor.config" ref="ue"></uediter>
    <button @click="returncontent">显示编辑器内容</el-button>
    <div>{{dat.content}}</div>
  </div>
</template>
<script>
  import uediter from '@/components/ue.vue';

  export default {
    data () {
      return {
        dat: {
          content: ''
        },
        ueditor: {
          value: '编辑器默认文字',
          config: {
            initialframewidth: 800,
            initialframeheight: 320
          }
        }
      }
    },
    methods: {
      returncontent () {
        this.dat.content = this.$refs.ue.getuecontent()
      }
    },
    components: {
      uediter
    },
  }
</script>

效果如下:

Vue2.0中集成UEditor富文本编辑器的方法

what's more: 服务端需要做的配置

配置完上述内容后,控制台可能会出现"后台配置项返回格式出错,上传功能将不能正常使用!"的报错,
我们在编辑器中上传图片或者视频,也会出现响应的报错,这是因为没有配置服务器的请求接口,在ueditor.config.js中,对serverurl进行配置:

// 服务器统一请求接口路径
, serverurl: 'http://172.16.254.49:83/file/ueditor'  //地址管你们后端要去