关于异步获取数据,富文本编辑器无法显示
效果:
1.解决方案:一定要在使用到wangEditor的组件中进行网络请求。
大多数wangEditor创建实例是在mounted()中,而异步获取后端数据也是在mounted中。所以大多数人会将它们分开写。
然后就会发现,后端数据可以拿到,wangEditor实例可以创建,但是wangEditor无法添加后端数据显示出来
原因,mounted()生命周期中,虽然可以操作data中的变量进行赋值操作,但是在同级作用域之外,变量的值会变成data()中的默认值。
也就是说,虽然你可以拿到后端的数据,并且可以在网络请求函数作用域打印,但是你发现,如果你将获取到后端的值,在mounted()中网络请求函数之外打印,结果是空的,这就造成了无法在wangEditor中直接赋值,或者添加数据
解决办法,将wangEditor的实例创建在网络请求到后台数据的函数中。
代码如下:(我进行了网络请求request的封装,需要的话自取)
关键代码
mounted () {
request({
url:'/getmannotice',
method:'post',
data:{
userid:this.userid
}
},
res=>{
if(res.data.code=='200')
{
this.getmannotice=res.data.notice;
// wangeditor
this.phoneEditor = new E('#EditorElem')
// 创建一个富文本编辑器
this.phoneEditor.create()
// 富文本内容
this.phoneEditor.txt.html()
this.phoneEditor.txt.append(this.getmannotice)
}
else{
this.$message.error('获取公告失败!')
}
},
err=>{
console.log(err)
this.$message.error('获取公告失败!')
})
}
request文件,使用时记得导入
import axios from "axios";
export function request(config,success,error)
{
const instance=axios.create({
baseURL: 'http://0.0.01',
timeout:5000,
method:'post'
})
instance(config).then(
res=>{
success(res)
})
.catch(err=>{
error(err)
})
}