這篇文章將為大家詳細講解有關Vue.js中如何使用Ueditor富文本編輯器,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
1. 總體思路
1.1 模塊化
vue的很大的一個優勢在于模塊化,我們可以通過模塊化實現頁面和邏輯的復用。所以可以把Ueditor重新封裝成一個.vue的模板文件。其他組件通過引入這個模板實現代碼復用。
1.2 數據傳輸
首先父組件需要設置編輯器的長度、寬度、初始文本,這些數據可以通過props來傳遞。編輯器中的文本變化可以通過vue自定義事件向父組件傳遞。
2. 具體實現步驟
2.1 引入關鍵的JS以及CSS文件
將以下文件全部拷貝到項目中
2.2 配置Ueditor.config.js
首先配置URL參數,我們需要將這個路徑指向剛才拷貝的文件的更目錄,注意這里最好使用相對路勁。
var URL = window.UEDITOR_HOME_URL || '/static/ueditor/';
然后是默認寬度高度的設置
,initialFrameWidth:null // null表示寬度自動 ,initialFrameHeight:320
其他功能的配置可以在官方文檔查看
2.3 創建編輯器模板
我們需要在編輯器模板中import Ueditor核心JS庫,并添加contentChange回調函數就大功告成了。
之所以使用import語法來引入核心JS庫是因為這樣更符合ES6模塊化的規范,我看到網上有人建議在main.js中引入JS,但是過早地引入JS可能導致頁面首次加載緩慢。
<template> <div ref="editor"></div> </template> <script> /* eslint-disable */ import '../../../assets/js/ueditor/ueditor.config'; import '../../../assets/js/ueditor/ueditor.all'; import '../../../assets/js/ueditor/lang/zh-cn/zh-cn'; import { generateRandonInteger } from '../../../vuex/utils'; export default { data() { return { id: generateRandonInteger(100000) + 'ueditorId', }; }, props: { value: { type: String, default: null, }, config: { type: Object, default: {}, } }, watch: { value: function value(val, oldVal) { this.editor = UE.getEditor(this.id, this.config); if (val !== null) { this.editor.setContent(val); } }, }, mounted() { this.$nextTick(function f1() { // 保證 this.$el 已經插入文檔 this.$refs.editor.id = this.id; this.editor = UE.getEditor(this.id, this.config); this.editor.ready(function f2() { this.editor.setContent(this.value); this.editor.addListener("contentChange", function () { const wordCount = this.editor.getContentLength(true); const content = this.editor.getContent(); const plainTxt = this.editor.getPlainTxt(); this.$emit('input', { wordCount: wordCount, content: content, plainTxt: plainTxt }); }.bind(this)); this.$emit('ready', this.editor); }.bind(this)); }); }, }; </script> <style> body{ background-color:#ff0000; } </style>
3. 編輯器的使用
使用編輯器模板的時候我需要通過props傳入config以及初始文本value。
<template xmlns:v-on="http://www.w3.org/1999/xhtml"> <div class="edit-area"> <ueditor v-bind:value=defaultMsg v-bind:config=config v-on:input="input" v-on:ready="ready"></ueditor> </div> </template> <script> import ueditor from './ueditor.vue'; export default { components: { ueditor, }, data() { return { defaultMsg: '初始文本', config: { initialFrameWidth: null, initialFrameHeight: 320, }, }; }, }; </script>
關于Vue.js中如何使用Ueditor富文本編輯器就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。