微信小程序中的editor组件放到自定义组件中去使用

  1. 下载官方提供的示例代码:editor示例代码
  2. 复制editor文件夹到自己自定义组件文件夹中
  3. 修改editor文件夹下的editor.js文件
    Page改成 -> Component
    添加properties,还有一些事件(onBindInput,onBindBlur,setContents)
Component({
  properties: {
    placeholder: String
  },
  data: {
    formats: {},
    readOnly: false,
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
  },
  methods: {
    readOnlyChange() {
      this.setData({
        readOnly: !this.data.readOnly
      })
    },
    onLoad() {
      const platform = wx.getSystemInfoSync().platform
      const isIOS = platform === 'ios'
      this.setData({ isIOS})
      const that = this
      this.updatePosition(0)
      let keyboardHeight = 0
      wx.onKeyboardHeightChange(res => {
        if (res.height === keyboardHeight) return
        const duration = res.height > 0 ? res.duration * 1000 : 0
        keyboardHeight = res.height
        setTimeout(() => {
          wx.pageScrollTo({
            scrollTop: 0,
            success() {
              that.updatePosition(keyboardHeight)
              that.editorCtx.scrollIntoView()
            }
          })
        }, duration)

      })
    },
    updatePosition(keyboardHeight) {
      const toolbarHeight = 50
      const { windowHeight, platform } = wx.getSystemInfoSync()
      let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
      console.log("editorHeight------------->", editorHeight)
      console.log("keyboardHeight------------->", keyboardHeight)
      this.setData({ editorHeight, keyboardHeight })
    },
    calNavigationBarAndStatusBar() {
      const systemInfo = wx.getSystemInfoSync()
      const { statusBarHeight, platform } = systemInfo
      const isIOS = platform === 'ios'
      const navigationBarHeight = isIOS ? 44 : 48
      return statusBarHeight + navigationBarHeight
    },
    /**编辑器内容改变时触发 */
    onBindInput(e) {
      this.triggerEvent('input', e.detail.html)
      // console.log("blur----------->", e)
    },
    /**编辑器失去焦点时触发 */
    onBindBlur(e) {
      this.triggerEvent('blur', e.detail)
      // console.log("blur----------->", e)
    },
    onEditorReady() {
      const that = this
      // 注意这个地方,加了.in(this),因为在自定义组件中应使用this.createSelectorQuery() 来代替 wx.createSelectorQuery()
      //https://developers.weixin.qq.com/miniprogram/dev/api/wxml/wx.createSelectorQuery.html
      wx.createSelectorQuery().in(this).select('#editor').context(function (res) {
        that.editorCtx = res.context
        // 通知主页面,不懂可去官方文档查看
		//https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/events.html#%E8%A7%A6%E5%8F%91%E4%BA%8B%E4%BB%B6
        that.triggerEvent('ready', that)
      }).exec()
    },
    /**初始化编辑器内容,html和delta同时存在时仅delta生效 */
    setContents(val) {
      this.editorCtx.setContents({
        html: val,
        success: function () {
          console.log('setContents success')
        }
      })
    },
    blur() {
      this.editorCtx.blur()
    },
    format(e) {
      let { name, value } = e.target.dataset
      if (!name) return
      // console.log('format', name, value)
      this.editorCtx.format(name, value)

    },
    onStatusChange(e) {
      console.log("---------------->", e)
      const formats = e.detail
      this.setData({ formats })
    },
    insertDivider() {
      this.editorCtx.insertDivider({
        success: function () {
          console.log('insert divider success')
        }
      })
    },
    clear() {
      this.editorCtx.clear({
        success: function (res) {
          console.log("clear success")
        }
      })
    },
    removeFormat() {
      this.editorCtx.removeFormat()
    },
    insertDate() {
      const date = new Date()
      const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
      this.editorCtx.insertText({
        text: formatDate
      })
    },
    insertImage() {
      const that = this
      wx.chooseImage({
        count: 3,
        success: function (res) {
			that.editorCtx.insertImage({
	          src: res.tempFilePaths[0],
	          data: {
	            id: 'abcd',
	            role: 'god'
	          },
	          width: '80%',
	          success: function () {
	            console.log('insert image success')
	          }
	        })          
        }
      })
    },
  }
})

  1. 修改editor.json
{
  "component": true,
  "usingComponents": {}
}
  1. 修改editor.wxss
    weui.wxss 我直接个注释了,感觉没用到
    iconfont.wxss 相对路径改成了绝对路径
    .container 的相对定位我去掉了,我不需要,样式就自己调吧

/* @import "../common/lib/weui.wxss"; */
@import "/components/editor/assets/iconfont.wxss";

.container {
  /* position: absolute; 
  top: 0; 
  left: 0;  */
  width: 100%;
}
/*后面的css省略了...和例子一样自己也可以微调*/
  1. 修改editor.wxml
    editorHeight 我直接写死了,示例中是用js计算的太长了没看
    就加了几个事件(bindblur(失去焦点触发),bindinput(编辑器中内容改变触发)),其他的都没动
<view class="container" style="height:{{editorHeight}}px;">
  <editor id="editor" class="ql-container" placeholder="{{placeholder}}" bindstatuschange="onStatusChange" bindready="onEditorReady" bindblur="onBindBlur" bindinput="onBindInput">
  </editor>
</view>

<!-- hidden="{{keyboardHeight > 0 ? false : true}}" -->
<view class="toolbar" catchtouchend="format"  style="bottom: {{isIOS ? keyboardHeight : 0}}px">
  <i class="iconfont icon-charutupian" catchtouchend="insertImage"></i>
  <i class="iconfont icon-format-header-2 {{formats.header === 2 ? 'ql-active' : ''}}" data-name="header" data-value="{{2}}"></i>
  <i class="iconfont icon-format-header-3 {{formats.header === 3 ? 'ql-active' : ''}}" data-name="header" data-value="{{3}}"></i>
  <i class="iconfont icon-zitijiacu {{formats.bold ? 'ql-active' : ''}}" data-name="bold"></i>
  <i class="iconfont icon-zitixieti {{formats.italic ? 'ql-active' : ''}}" data-name="italic"></i>
  <i class="iconfont icon-zitixiahuaxian {{formats.underline ? 'ql-active' : ''}}" data-name="underline"></i>
  <i class="iconfont icon--checklist" data-name="list" data-value="check"></i>
  <i class="iconfont icon-youxupailie {{formats.list === 'ordered' ? 'ql-active' : ''}}" data-name="list" data-value="ordered"></i>
  <i class="iconfont icon-wuxupailie {{formats.list === 'bullet' ? 'ql-active' : ''}}" data-name="list" data-value="bullet"></i>
</view>

主页面.json中

{
  "usingComponents": {
    "custom-editor": "/components/editor/editor"
  }
}

主页面.wxml中
placeholder 与 editor 中的 properties.placeholder 的值是绑定的
id 是用来获取组件的实例
获取组件实例

<custom-editor id="editor" bind:input="onBindInputEditor" bind:ready="onBindReadyEditor" placeholder="请作答..."></custom-editor>

主页面.js
添加事件

    /**监听编辑器初始化完成时触发 */
    onBindReadyEditor(e){
        console.log('onBindReadyEditor---------------->', e.detail)
        e.detail.setContents('666')
        // 或者,获取组件实例,调用组件的事件
        //let editor = this.selectComponent("#editor")
		//editor.setContents('666666')
    },

    /**编辑器内容改变时触发 */
    onBindInputEditor(e){
        console.log("onBindInputEditor--------------------------->", e.detail)                 
    },
    /**编辑器失去焦点 */
    不写了...写法一样

相关博文
微信小程序editor组件
微信小程序自定义组件
组件间的通信与事件
EditorContext-API

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值