vue textarea空格和換行處理

應(yīng)用需求:在textarea中輸入文字,提交給后臺(tái)后,后臺(tái)輸出在另一個(gè)頁面,文字按原格式顯示。

在提交接口前處理綁定的數(shù)據(jù)

<el-input v-model="temp.content" :value="temp.content" type="textarea" :autosize="{ minRows: 4, maxRows: 20}"  placeholder="請(qǐng)輸入內(nèi)容" 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;')

方法二:識(shí)別換行后 分別加上p標(biāo)簽
這里需要注意的是 在傳給接口前還需要將添加p標(biāo)簽后的數(shù)組形式轉(zhuǎn)換成字符串

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:用于設(shè)置或返回元素的內(nèi)容是否可編輯。
給任意標(biāo)簽如div或p標(biāo)簽設(shè)置屬性contentEditable = true,則p標(biāo)簽或div標(biāo)簽等為可編輯標(biāo)簽

            <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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容