1. 程式人生 > >富文字編輯器 wangEditor 使用

富文字編輯器 wangEditor 使用

軟體特點

  • 支援 npm 直接引用
  • 支援響應式,自動縮放
  • 沒有官方的例項銷燬方案,專案中使用的是作者在github給出的臨時方案
  • 支援一個頁面多個編輯器
  • 不支援一個頁面多個編輯器同時使用地圖
  • 後端需要進行相應配置

安裝 wangEditor

npm install wangeditor --save

程式碼引入 wangEditor (vue環境)

<div type="text/plain" id="account--editor"></div>
#account--editor {
    width: 100%;
    min-height: 330px;
    height: auto;
}
<script type="text/javascript">
import WangEditor from 'wangeditor';
export default {
    data(){
        return{
            dataInterface: {
                editorUpImgUrl: 'http://xxxx'  // 編輯器插入的圖片上傳地址
            },
            editor: '',  // 存放例項化的wangEditor物件,在多個方法中使用
        }
    },
    ready(){
        this
.createEditor(); }, beforeDestroy(){ this.destroyEditor(); }, methods: { createEditor(){ // 建立編輯器 this.editor = new WangEditor('account--editor'); this.initEditorConfig(); // 初始化編輯器配置,在create之前 this.editor.create(); // 生成編輯器 this
.editor.$txt.html('<p>要初始化的內容</p>'); // 初始化內容 $('#account--editor').css('height', 'auto'); // 使編輯器內容區自動撐開,在css中定義min-height }, destroyEditor(){ // 銷燬編輯器,官方沒有給出完美方案。此方案是作者給出的臨時方案 this.editor.destroy(); // 這個沒有完全銷燬例項,只是作了隱藏 // $('#account--editor').remove(); // 不報錯的話,這一步可以省略 this.editor = null; WangEditor.numberOfLocation--; // 手動清除地圖的重複引用,作者的臨時解決方案。否則單頁面來回切換時,地圖報錯重複引用 }, initEditorConfig(){ // 初始化編輯器配置 this.editor.config.fontsizes = { // 字號配置,增加14px // 格式:'value': 'title' 1: '12px', 2: '13px', 3: '14px', 4: '16px', 5: '18px', 6: '24px', 7: '32px', 8: '48px' }; this.editor.config.uploadImgUrl = this.dataInterface.editorUpImgUrl; // 圖片上傳地址 this.editor.config.uploadImgFileName = '_img'; // 統一指定上傳的檔案name,需要指定。否則預設不同的上傳方式是不同的name const usersecret = window.localStorage.getItem('usersecret'); // 獲取 usersecret this.editor.config.uploadParams = { // 自定義上傳引數配置 usersecret: usersecret }; }, getEditorContent(){ // 獲取編輯器 內容區內容 this.editorContent = this.editor.$txt.html(); // 獲取 html 格式 // this.editor.$txt.text(); // 獲取純文字 // this.editor.$txt.formatText(); // 獲取格式化後的純文字 }, } } </script>

圖片上傳 server 端配置

/**
 * 圖片上傳 圖片上傳注意上傳目錄的許可權
 */
public function editorUploadImg()
{   
    $upload_ret = D('Upload', 'Service')->uploadImg('_img'); 
    echo 'http://'.$_SERVER['HTTP_HOST'].DIRECTORY_SEPARATOR.$upload_ret;
    exit();
}
  • 後端注意上傳的目錄許可權,可能需要777