在用vscode+uni-app开发小程序时遇到了个使用原生edit富文本编辑器报错的问题,按照官方的文档去写一直报错,官网用的vue2的写法,这里我用的vue3
先看报错写法以及报错内容
template中:
<editor id="editor" ref="editorRef" class="ql-container"
:placeholder="placeholder" @statuschange="onStatusChange"
:show-img-resize="true" @ready="onEditorReady" @input="getCtx">
</editor>
ts中:
const onEditorReady = () => {
// 富文本节点渲染完成
var htmls = props.value
if (htmls) {
let contents = JSON.stringify(htmls)
console.log(contents)
nextTick(() => {
uni.createSelectorQuery().select("#editor").context((res: any) => {
console.log('res', res);
editorCtx.value = res.context;
editorCtx.value?.setContents({
html: htmls,
delta: contents
})
}).exec();
})
}
}
报错:res输出为null,没有获取到dom元素,并且富文本中无法渲染内容
解决方法:
vue3中需要修改写法
import { ref, getCurrentInstance, nextTick } from 'vue';
const instance = getCurrentInstance();
const onEditorReady = () => {
// 富文本节点渲染完成
var htmls = props.value
if (htmls) {
let contents = JSON.stringify(htmls)
console.log(contents)
const query = uni.createSelectorQuery().in(instance);
query.select("#editor").context((res: any) => {
console.log('editorRef.value', res);
editorCtx.value = res.context;
console.log('editorCtx.value', editorCtx.value);
editorCtx.value?.setContents({
html: htmls,
delta: contents
})
}).exec();
}
}
重新编译:正常打印,并且富文本中正常渲染出内容
亲测uni-app和小程序中都显示正常!
如有错误请及时指正!