No.1问题:Vue项目中使用uedior的时候总是报错Cannot read property 'offsetWidth' of null.
解决:
一、出现这个问题首先应该想到:offsetWidth这个属性的主体是谁?报错地方在哪里
使用
// 此处的ID是我的UEditor对应的容器ID
console.log(document.querySelector("#contentEditor")) // null
二、经过上述的打印判断到了当前所对应的元素的内容位Null,表明当前元素并没有被创建。
上一步的日志,在vue生命周期中的mounted中,为什么没有打印出值呢?因为当前元素在mounted中只是创建了一次,对应的DOM更新,需要再调用一次updated钩子。
所以最简单的办法就是在mounted的方法中加上一句
this.$nextTick(()=>{
console.log(document.querySelector("#contentEditor"));
})
// <div id="contentEditor" style="width:400px;height:300px;"></div>
可以看到当前DOM已经渲染,在此可以创建editor实例;
// 确保当前语句在执行之前已经引入了ueditor的包
/**
* 此处是我在的ueditor
* import "../../../public/lib/ueditor/ueditor.config.js";
* import "../../../public/lib/ueditor/ueditor.all.js";
* import "../../../public/lib/ueditor/lang/zh/zh-cn.js";
*/
this.editor = UE.getEditor("contentEditor") // this.editor是我在data中定义的一个变量,用于接收富文本实例,以便于再其他地方使用editor的API
至此以后就可以使用了。
No.2问题:在切换路由之后发现ueditor不显示了?
解决:
在组件或者任何路由切换的时候,销毁富文本实例。
UE.delEditor("contentEditor")
之前在网上看到过另一个方法就是:UE.getEditor("contentEditor").destory() , 不过我没试过这个方法~