项目场景:
进入页面初始化时,需要填入之前预填写的富文本内容,使用uniapp中editor组件setContents方法为富文本编辑器设置内容时,内容有时不时设置不成功,微信小程序同样适用
问题描述
使用uniapp中editor组件setContents方法为富文本编辑器设置内容时,在mounted时调用setContents方法,富文本内容有时设置不成功
样例代码:
<template>
<editor id="editor"></editor>
</template>
<script>
export default {
data() {
html: '<p>富文本测试</p>',
editorCtx : ''
},
mounted() {
let _this = this
// #ifdef APP-PLUS || H5 ||MP-WEIXIN
uni.createSelectorQuery().select('#editor').context((res) => {
_this.editorCtx = res.context //uni.createSelectorQuery获取editor 组件对应的 editorContext实例
}).exec()
_this.editorCtx.setContents({
'html': _this.html,
success: (res)=> {
console.log(res,"res")
},
fail:(err)=> {
console.log(err,"err")
}
})
// #endif
}
}
原因分析:
在mounted时调用setContents方法会返回两个回调,一个成功回调,一个失败回调
通过在setContents中打印回调函数结果,分析得知是setContents调用失败即未准备好
- 成功时函数回调图片如下
- 报错时函数回调图片如下
解决方案:
通过在setContents成功的回调时设置定时器(简单粗暴),通过监听isOk值判断setContents函数是否成功,成功时清除定时器。
解决代码如下:
<template>
<editor id="editor"></editor>
</template>
<script>
export default {
data() {
html: '<p>富文本测试</p>',
editorCtx : '',
isOk: false
},
watch: {
isOk() { //监听isOk属性,为true时说明setContents已执行成功的回调,此时清除timer定时器
this.isOk && clearInterval(this.timer)
}
},
mounted() {
let _this = this
// #ifdef APP-PLUS || H5 ||MP-WEIXIN
uni.createSelectorQuery().select('#editor').context((res) => {
_this.editorCtx = res.context //uni.createSelectorQuery获取editor 组件对应的 editorContext实例
}).exec()
_this.timer = setInterval(() => { //设置timer定时器触发setContents函数
_this.editorCtx.setContents({
'html': _this.html,
success: (res)=> {
console.log(res,"res")
_this.isOk = true //成功的回调,说明富文本已设置内容,此时将isOk属性设为true
},
fail:(err)=> {
console.log(err,"err")
}
})
})
// #endif
}
}
!!修改版!!
防止app端卡死,新增500毫秒延迟和loading效果,增加用户体验
解决代码如下:
<template>
<editor id="editor"></editor>
</template>
<script>
export default {
data() {
html: '<p>富文本测试</p>',
editorCtx : '',
isOk: false
},
watch: {
isOk() { //监听isOk属性,为true时说明setContents已执行成功的回调,此时清除timer定时器
this.isOk && clearInterval(this.timer) && uni.hideLoading()
}
},
mounted() {
let _this = this
// #ifdef APP-PLUS || H5 ||MP-WEIXIN
uni.createSelectorQuery().select('#editor').context((res) => {
_this.editorCtx = res.context //uni.createSelectorQuery获取editor 组件对应的 editorContext实例
}).exec()
uni.showloading({ //增加loading效果,优化用户体验
title: "加载中"
})
_this.timer = setInterval(() => { //设置timer定时器触发setContents函数
_this.editorCtx.setContents({
'html': _this.html,
success: (res)=> {
console.log(res,"res")
_this.isOk = true //成功的回调,说明富文本已设置内容,此时将isOk属性设为true
},
fail:(err)=> {
console.log(err,"err")
}
})
}, 500) //添加一个500毫秒的延迟,减少app端压力(兼容app端)
// #endif
}
}