做近代史纲要题的网站,石景山周边网站建设,个人网站的优点,做网站的手机软件Vue 中#xff0c;直接使用包含 \n 的字符串进行渲染时#xff0c;换行符不会被识别为 HTML 的换行#xff0c;因为 Vue 默认会将其视为普通文本。
对此提供两种解决办法
方法一#xff1a;使用 v-html 指令替换 \n 为 br
templatediv v-html…Vue 中直接使用包含 \n 的字符串进行渲染时换行符不会被识别为 HTML 的换行因为 Vue 默认会将其视为普通文本。
对此提供两种解决办法
方法一使用 v-html 指令替换 \n 为 br
templatediv v-htmlformattedText/div
/templatescript
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 属性
templatediv classtext-container{{ originalText }}/div
/templatescript
export default {data() {return {originalText: This is the first line.\nThis is the second line.};}
};
/scriptstyle scoped
.text-container {white-space: pre-line;
}
/style在 data 中同样定义了 originalText 包含换行符的字符串。 在模板中直接使用双花括号 {{ originalText }} 进行文本渲染。 在 style 中为包含文本的元素添加 white-space: pre-line 的 CSS 属性它会将连续的空格合并为一个空格并且将 \n 作为换行符进行显示。