小程序在去年5月的 v2.7.0 版本新增了組件editor富文本編輯器,但對於像我這種開發新手,要熟練使用還是有一定難度。所以記錄一下我的學習過程,希望對大家有幫助。
小程序有詳細的微信開發文檔,所以對於開發新手,我建議不要一味的複製別人的博客代碼,一定要學看和使用開發文檔。
首先熟悉一下開發文檔關於editor富文本編輯器的內容。
基礎庫低於2.7.0要做兼容處理。
官方推薦用delta解析插入內容。
下面是組件使用過程:(可參照官方的示例代碼)
- wxml引入組件(看開發文檔的屬性)
//富文本編輯器組件引用
<editor id="editor"
class="ql-container"
placeholder="富文本編輯器"
bindstatuschange="onStatusChange"
bindready="onEditorReady">
</editor>
//創建按鈕,觸發獲取富文本編輯器內容
<view class="action text-green" bindtap="getContent">發表</view>
2.js初始化富文本編輯器
//初始化富文本編輯器
onEditorReady() {
const that = this
const query = wx.createSelectorQuery()//創建節點查詢器
query.in(that).select('#editor').context()//選擇id=editor的節點,獲取節點內容信息
query.exec(function(res){
that.editorCtx = res.context
console.log(res.context);
})
}
3.獲取編輯器內容(查看開發文檔EditorContext)
//獲取編輯器輸入的內容
getContent() {
const that = this
that.editorCtx.getContents({
success: function (res) {
console.log(res.detla)
}.
fail: function (error){
console.log(error)
}
注意:查看EditorContext.getContents(Object object),success返回參數如下,所以res不是res.data, 可以是res.html 、res.text、res.delta,官方文檔推薦使用delta, 所以這裏選擇delta, 在數據庫也保存的是delta對象。
4.顯示delta對象。
前面我們將delta對象轉換爲字符串存入數據庫,在顯示時將delta對象取出顯示,查看EditorContext.getContents(Object object)。
wxml
//同樣引入富文本編輯器組件editor,並將其設置爲只讀read-only
<editor id="content" class="ql-container1" read-only="true">
</editor>
js
onLoad: function (options) {
let that = this
//content是從數據庫獲取的數據裏的delta字符串,然後裝換爲json
var content = JSON.parse(that.data.contentInfo.content)
var query = wx.createSelectorQuery();//創建節點查詢器
query.in(that).select('#content').context(function (res) {
res.context.setContents({
delta: content,
success: function (res) {
// console.log(res.data)
},
fail: function (error) {
console.log(error)
}
})
}).exec()
}
這樣,便完成了編輯器組件的引用以及編輯器內容的顯示了。
當然編輯器裏還需進行其他功能設置,如插入圖片、設置樣式、清空編輯器等,這些均可根據開發文檔的editor與EditorContext,按照上面進行編寫。可參考官方的demo。圖片插入上傳可看本博客下一篇文章。