vue textarea空格和换行处理

应用需求:在textarea中输入文字,提交给后台后,后台输出在另一个页面,文字按原格式显示。

在提交接口前处理绑定的数据

<el-input v-model="temp.content" :value="temp.content" type="textarea" :autosize="{ minRows: 4, maxRows: 20}"  placeholder="请输入内容" class="filter-item" clearable />

方法一:可以用replace替换空格和换行

this.temp.content = this.temp.content.replace(/\n/g, '<br/>')
this.temp.content = this.temp.content.replace(new RegExp(' ', 'gm'), '&nbsp;')

方法二:识别换行后 分别加上p标签
这里需要注意的是 在传给接口前还需要将添加p标签后的数组形式转换成字符串

this.temp.content = this.temp.content.replace(new RegExp(' ', 'gm'), '&nbsp;') // gm 全局替换
const arr = []
this.temp.content.split('\n').forEach(item => {
    arr.push(`<p>${item.trim()}</p>`)
 })
this.temp.content = arr.join('')

方法三:使用属性contentEditable
属性contentEditable:用于设置或返回元素的内容是否可编辑。
给任意标签如div或p标签设置属性contentEditable = true,则p标签或div标签等为可编辑标签

            <div ref="content" contenteditable="true" style="border:1px solid #C0C4CC;height:100%:overflow-y:auto;" @input="changeTxt" v-html="temp.content">{{ temp.content }}</div>

changeTxt() {
      this.tempContent = this.$refs.content.innerHTML
    },
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容