问题描述
在项目中针对于文本域和表格,在文本域输入内容,回车换行之后,点击保存按钮时将数据传给后台,后端返回的数据中是不支持前端进行空格和换行显示的,这是因为在文本域中输入空格和换行会被转换成为特殊字符为
\s
和\r\n
解决方案
可以使用正则表达式进行替换,当点击保存或提交按钮后,可以转换一次
let param = {
y27x00: this.middleForm.y27x00,
a0000: this.middleForm.a0000,
y27x21: this.companyForm.y27x21
.replace(/[\r\n]/g, "<br/>")
.replace(/\s/g, " "), //单位意见
y27x22: this.companyForm.y27x22, //填写时间
y27x23: this.companyForm.y27x23
.replace(/[\r\n]/g, "<br/>")
.replace(/\s/g, " "), //备注
y27x44: this.companyForm.y27x44, //填表人
};
然后保存提交成功后,会重新调用后台接口进行刷新,表格数据可以使用v-html渲染即可支持换行和空格,但是文本域并不支持,所以针对后台回显数据,我们还需要在做一次处理
let reg = new RegExp("<br/>", "g"); let reg2 = new RegExp(" ", "g"); //替换</br> 和 针对需要渲染的文本域数据在做一次转换即可 this.companyForm.y27x21 = res.data.y27x21.replace(reg, "\r\n").replace(reg2, " "); this.companyForm.y27x23 = res.data.y27x23.replace(reg, "\r\n").replace(reg2, " ");