vue.js中不使用pre相关样式实现字符串换行的可行方法有哪些?
Vue.js 字符串换行实现方案(不使用pre标签与white-space相关属性)
以下两种方案均可满足需求,无需依赖pre标签或white-space: pre/pre-wrap属性:
方案1:使用
v-html渲染换行标签
先将字符串中的\n全局替换为<br>标签,再通过v-html指令绑定文本内容,代码实现更简洁,适合文本内容完全由内部可控的场景。
示例代码:created() { this.buttons = [ { id: 1, text: "Button \n 1", }, { id: 2, text: "Button \n 2", }, { id: 3, text: "Button \n 3", } ].map(item => { // 替换所有换行符为br标签,兼容低版本浏览器可改为 replace(/\n/g, '<br>') item.text = item.text.replaceAll('\n', '<br>') return item }) }模板部分:
<template> <!-- 循环渲染按钮 --> <button v-for="btn in buttons" :key="btn.id" v-html="btn.text" ></button> </template>注意:如果文本包含用户输入内容,该方案存在XSS风险,请优先使用方案2
方案2:拆分字符串为数组循环渲染
将文本按\n分割为数组,在模板中遍历每一行内容单独渲染,行之间插入<br>标签实现换行,无安全性问题,适配所有场景。
无需修改原JS逻辑,直接调整模板即可:<template> <button v-for="btn in buttons" :key="btn.id"> <span v-for="(line, idx) in btn.text.split('\n')" :key="idx" > {{ line }} <!-- 最后一行不需要加换行标签 --> <br v-if="idx !== btn.text.split('\n').length - 1"> </span> </button> </template>
内容的提问来源于stack exchange,提问作者EmielV
相关产品推荐
相关产品推荐

