要实现文本格式的保存和回显,除了富文本编辑器以外,还有个简单的方法,毕竟只是要段落格式的话,富文本编辑器就显得太复杂了,具体实现如下:
首先,注意是文本输入框type="textarea"
<el-form-item label="描述" prop="describe">
<el-input
v-model="form.describe"
type="textarea"
:rows="6"
maxlength="400"
show-word-limit
></el-input>
</el-form-item>
转化格式的方法
textTohtml(val){
return val.replace(/<(.+?)>/gi, "<$1>")
.replace(/ /gi, " ")
.replace(/\n/gi, "<br/>");
}
在新增数据调用接口的时候,使用转化格式的方法,再提交数据
onSubmit() {
this.$refs["form"].validate((valid) => {
if (valid) {
const describe = this.textTohtml(this.form.describe);
// 调用新增接口
addList({
...this.form,
describe
}).then((res) => {
// 成功后的操作
// ...
});
} else {
this.$message.error("必填项不能为空!");
return false;
}
});
},
编辑回显的操作:
同上述转化方法,只不过是将数据转化回来,方法如下:
htmlToText(val) {
return val.replace(/<br\/>/g, "\n")
.replace(/ /g, " ")
.replace(/<$1>/gi, "<(.+?)>");
},
在初始化回显的时候调用
this.form.describe = this.htmlToText(this.form.describe);
详情的时候就不用多说了,因为我这里详情的时候是用span标签展示,所以直接用v-html就好啦
<span v-html="form.describe"></span>