vue textarea空格和换行处理

2020-04-30  本文已影响0人  Do_Du

应用需求:在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
上一篇 下一篇

猜你喜欢

热点阅读