当前位置: 首页 > news >正文

vue \n 换行不不显示

Vue 中,直接使用包含 \n 的字符串进行渲染时,换行符不会被识别为 HTML 的换行,因为 Vue 默认会将其视为普通文本。

对此提供两种解决办法

方法一:使用 v-html 指令替换 \n 为 <br>

<template><div v-html="formattedText"></div>
</template><script>
export default {data() {return {originalText: "This is the first line.\nThis is the second line."};},computed: {formattedText() {return this.originalText.replace(/\n/g, '<br>');}}
};
</script>

在 data 中定义了 originalText,其中包含了 \n 作为换行符的字符串。
通过 computed 属性 formattedText,使用 replace(/\n/g, ‘<br>’) 方法将 \n 替换为 <br> 元素。
在模板中使用 v-html 指令将 formattedText 作为 HTML 进行渲染,这样 <br> 元素会被解析为换行效果。

方法二:使用 white-space: pre-line CSS 属性

<template><div class="text-container">{{ originalText }}</div>
</template><script>
export default {data() {return {originalText: "This is the first line.\nThis is the second line."};}
};
</script><style scoped>
.text-container {white-space: pre-line;
}
</style>

在 data 中同样定义了 originalText 包含换行符的字符串。
在模板中直接使用双花括号 {{ originalText }} 进行文本渲染。
在 style 中为包含文本的元素添加 white-space: pre-line 的 CSS 属性,它会将连续的空格合并为一个空格,并且将 \n 作为换行符进行显示。

http://www.lryc.cn/news/520741.html

相关文章:

  • GPT 系列论文精读:从 GPT-1 到 GPT-4
  • 在 Ubuntu 上安装和配置 Redis
  • Excel中双引号问题
  • 【机器学习】主动学习-增加标签的操作方法-流式选择性采样(Stream-based selective sampling)
  • elementUI项目中,只弹一个【token过期提示】信息框的处理
  • SpringBoot开发—— SpringBoot中如何实现 HTTP 请求的线程隔离
  • 【LLM】25.1.11 Arxiv LLM论文速递
  • 单片机实物成品-012 酒精监测
  • 使用葡萄城+vue实现Excel
  • 【Uniapp-Vue3】@import导入css样式及scss变量用法与static目录
  • 跟我学C++中级篇——字节序
  • Linux网络编程5——多路IO转接
  • Redis常见
  • 提升 PHP 编码效率的 10 个实用函数
  • 设计模式 行为型 访问者模式(Visitor Pattern)与 常见技术框架应用 解析
  • golang之数据库操作
  • 对话新晋 Apache SeaTunnel Committer:张圣航的开源之路与技术洞察
  • Mac 删除ABC 输入法
  • 《机器学习》之K-means聚类
  • 日常工作之 Elasticsearch 常用查询语句汇总
  • WeakAuras NES Script(lua)
  • JVM 触发类加载的条件有哪些?
  • Android实战经验篇-增加系统分区
  • 深入学习 Python 量化编程
  • 机器学习笔记——特征工程
  • 4种革新性AI Agent工作流设计模式全解析
  • 【入门级】计算机网络学习
  • 安装 Jenkins 后无法访问用户名或密码且忘记这些凭证怎么办?
  • day08_Kafka
  • 安装conda 环境