laravel+vue组合的项目中引入ueditor方式(打包成组件形式)

前言:最近写东西需要用到ueditor,并且需要是在vue组件中引入。

(本博客默认你已经配置了laravel+vue的项目环境,如果还没有配置好的的小伙伴,可以看看我的另一篇文章,链接:

https://www.laike.net/article/122369.htm )

1、下载editor

这个直接去ueditor的官网下载其PHP版本的就可以了,没什么好说的

2、移到项目目录中(主要讲如何放置配置文件和静态资源文件)

打开下载好的ueditor目录,如果版本没有错也没出什么问题,应该就会看到如下目录及文件

当然,放置好了配置文件,剩下的四个目录我们就直接放在laravel默认的静态资源目录public/js下面,像这样:

然后编写我们的ueditor组件,这里为了方便喜欢“偷懒”小伙伴们😄,就不放图片了,直接上代码(是不是很贴心)

<template>
  <div :id="id">
  </div>
</template>
<style scoped>
</style>
<script>
import './ueditor.config.js'
import './ueditor.all.min.js'        //引入相应的配置文件,具体路径请根据自己配置文件放置的路径以及公共组件定义的路径自行修改
import './ueditor.parse.min.js' 
import './lang/zh-cn/zh-cn.js'

 

export default {
  props: {
  },
  data(){
    return {
      id: Math.ceil(Math.random()*100000) + 'editor'
    }
  },
  mounted() {
    this.editor = UE.getEditor(this.id)  // 获取编辑器实例化的对象
  },
  methods: {
    getUEContent() { // 获取内容方法
    return this.editor.getContent()
  }
  }
}
</script>

好了,我们的公共编辑器组件就已经定义好啦。

可能会有些小伙伴觉得ueditor的工具栏实在是太多了,好多都是自己几乎用不到的,放在那里占地方不说,还降低了我们项目的加载速度,这里也许有些看过ueditor.config.js 配置文件的小伙伴应该会看到这样一项配置:

这里我们看到它的注释已经明确的告诉我们它的作用了:工具栏上的所有的功能按钮和下拉框,可以在new编辑器的实例时选择自己需要的重新定义

所以很简单了,想要精简编辑器的小伙伴们可以直接在我们的公共ueditor组件的生命周期函数mounted里覆盖此配置就好啦,附上一个我自己配置的代码:

mounted() {
  window.UEDITOR_CONFIG.toolbars = [[
    'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain',     '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', '|',
    'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'fontfamily', 'fontsize'
  ]]
  this.editor = UE.getEditor(this.id)
}

4、使用ueditor组件

到这里我们已经可以直接在我们其他任意的vue组件里使用我们的公共组件了:

在script标签中直接引入公共组件的UEditor.vue 文件,像这样:import UE from '../editor/UEditor.vue';

然后注册该组件:

components: {
  UE
}

接下来我们就可以直接在template模板中使用UE组件了:

<template lang="html">
  <div id="add">
    <div id="myueditor">
      <UE ref="ue"></UE>
    </div>

  </div>

</template>

这里我们使用了ref给组件注册了引用信息,这样我们就可以在这个父组件里调用我们编辑器组件的获取内容方法getUEContent()(这个方法调用了ueditor的getContent()方法,忘记的小伙伴可以去上面或者自己的代码里回顾一下),像这样:

<button @click="getUEContent()">获取内容</button>//模版里定义一个button绑定getUEContent()方法

然后注册getUEContent()方法:

methods: {
  getUEContent() {
    let content = this.$refs.ue.getUEContent();//在这里调用了子组件ueditor组件的getContent()方法
    this.$notify({
      title: '获取成功,可在控制台查看!',
      message: content,
      type: 'success'
    });
    console.log(content)
  }

}

好了,大功告成,赶紧去试试你的编辑器吧!