uniapp使用富文本组件editor获取不到data内数据的问题

发布时间 2024-01-04 11:34:29作者: MosterSeven

uniapp使用富文本组件editor获取不到data内数据的问题

vue2 在使用 uniapp 官方提供的 editor 富文本编辑器组件时,代码需求需要获取到富文本组件内的输入值并通过接口发送给后端。

使用uniapp官方函数 editorContext.getContents(OBJECT) 可以获取到富文本组件内内容,但是在使用的时候发现无论如何都没办法把获取到的内容存入 data(){} 内。

submit() {
    // this.editorCtx 是 editor 组件对应的 editorContext 实例
    this.editorCtx.getContents({
		success: function(res) {
	            console.log('success', res);
	            // 获取富文本组件内内容并存入record内
		    this.record = res.text;
	            console.log(this.record); // 打印出来的值为res.text内的值
		},
		fail: function(res) {
	            console.log('fail', res);
		}
    })
    console.log(this.record); // 打印出来的值为null
    
    ...请求后端接口
}

最开始以为是函数执行顺序的问题,所以尝试在 submit 函数前加上 async await
但是添加后依然没有作用。

async submit() {
    await this.editorCtx.getContents({
		success: function(res) {
	            console.log('success', res);
		    this.record = res.text;
		},
		fail: function(res) {
	            console.log('fail', res);
		}
    })
    console.log(this.record); // 打印出来的值仍然为null
    
    ...请求后端接口
}

然后突然想到,可能是获取到的 res.text 根本没有存到 data 内的 record 里面去,而是存到了另一个也叫 record 的变量里,所以才会导致在 getContents 外获取 record 的时候拿到的值是 null


会导致这种问题只有一种可能,那就是 因为 this 的指向变了

所以在使用 getContents 前先把 this 指向固定成 _this,在 getContents 内使用 _this 替代 this

async submit() {
    let _this = this;
    await this.editorCtx.getContents({
		success: function(res) {
	            console.log('success', res);
		    _this.record = res.text;
		},
		fail: function(res) {
	            console.log('fail', res);
		}
    })
    console.log(this.record); // 打印出来的值为res.text内的值
    
    ...请求后端接口
}

最后,成功获取到富文本组件 editor 内的输入值,并存入到 data(){} 内。