1. 程式人生 > >vue2.0專案中使用百度Ueditor富文字編輯器

vue2.0專案中使用百度Ueditor富文字編輯器

1.首先下載靜態檔案

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

2.然後,進行配置

首先把官網下載的Ueditor資源,放入靜態資源src/static中。

修改ueditor.config.js中的window.UEDITOR_HOME_URL配置,如下圖:

 

3.在main.js中引入

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

4.開發公共元件

開發公共元件,可設定填充內容defaultMsg,配置資訊config(寬度和高度等),並提供獲取內容的方法。

<template>
  <div>
    <script id="editor" type="text/plain"></script>
  </div>
</template>
<script>
  export default {
    name: 'UE',
    data () {
      return {
        editor: null
      }
    },
    props: {
      defaultMsg: {
        type: String
      },
      config: {
        type: Object
      }
    },
    mounted() {
      const _this = this;
      this.editor = UE.getEditor('editor', this.config); // 初始化UE
      this.editor.addListener("ready", function () {
        _this.editor.setContent(_this.defaultMsg); // 確保UE載入完成後,放入內容。
      });
    },
    methods: {
      getUEContent() { // 獲取內容方法
        return this.editor.getContent()
      }
    },
    destroyed() {
      this.editor.destroy();
    }
  }
</script>

5.使用

當我們需要使用富文字編輯器時,直接呼叫公共元件即可

<template>
  <div class="components-container">
    <button @click="getUEContent()">獲取內容</button>
    <div class="editor-container">
      <UE :defaultMsg=defaultMsg :config=config ref="ue"></UE>
    </div>
  </div>
</template>
<style>
  .info{
    border-radius: 10px;
    line-height: 20px;
    padding: 10px;
    margin: 10px;
    background-color: #ffffff;
  }
</style>
<script>
  import UE from '../../components/ue/ue.vue';
  export default {
    components: {UE},
    data() {
      return {
        defaultMsg: '這裡是UE測試',
        config: {
          initialFrameWidth: null,
          initialFrameHeight: 350
        }
      }
    },
    methods: {
      getUEContent() {
        let content = this.$refs.ue.getUEContent();     
        console.log(content)
      }
    }
  };
</script>

如果有嚴格模式報錯

Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them...

這個問題是因為專案中的使用的babel預設添加了use strict造成,可參考 https://segmentfault.com/q/1010000007415253
我採用的是連結中答案的第三種方式:添加了babel-plugin-transform-remove-strict-mode,並在.babelrc裡新增下列程式碼

{
  "plugins": ["transform-remove-strict-mode"]
}

注:ES6的模組自動採用嚴格模式,不管你有沒有在模組頭部加上"use strict";

效果圖如下: