小程序开发笔记(二):微信小程序富文本编辑器editor的使用

  小程序在去年5月的 v2.7.0 版本新增了组件editor富文本编辑器,但对于像我这种开发新手,要熟练使用还是有一定难度。所以记录一下我的学习过程,希望对大家有帮助。
  小程序有详细的微信开发文档,所以对于开发新手,我建议不要一味的复制别人的博客代码,一定要学看和使用开发文档。
  首先熟悉一下开发文档关于editor富文本编辑器的内容。

基础库低于2.7.0要做兼容处理。
官方推荐用delta解析插入内容。

下面是组件使用过程:(可参照官方的示例代码)

  1. 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。图片插入上传可看本博客下一篇文章。



评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值