You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在BootstrapVue的b-modal中将斜杠替换为换行并正确展示换行效果

问题根因

HTML 默认会将文本中的连续空白字符(包括\n换行符、制表符、多个空格)合并为单个空格展示,因此控制台打印能正常识别的\n换行,渲染到的DOM结构中就会失效。

可行解决方案

方案1:添加CSS样式控制(最推荐)

给模态框内的文本容器添加white-space: pre-line属性,该属性会保留文本中的换行符,同时也支持内容超出宽度时自动换行,不需要修改原有的字符串处理逻辑:

<template>
  <b-modal title="内容展示">
    <div class="text-wrapper">{{ newString }}</div>
  </b-modal>
</template>

<script>
export default {
  data() {
    return {
      actualString: "Hello / my name / is B0BBY / how / are you ?"
    }
  },
  computed: {
    newString() {
      return this.actualString.replaceAll(" / ", "\n")
    }
  }
}
</script>

<style scoped>
.text-wrapper {
  white-space: pre-line;
}
</style>

方案2:替换为HTML换行标签渲染

将分隔符替换为<br>标签,配合v-html指令渲染内容:

<template>
  <b-modal title="内容展示">
    <div v-html="newString"></div>
  </b-modal>
</template>

<script>
export default {
  computed: {
    newString() {
      return this.actualString.replaceAll(" / ", "<br>")
    }
  }
}
</script>

注意:如果待渲染字符串包含用户提交的不可信内容,使用v-html存在XSS注入风险,这种场景不推荐使用该方案。

方案3:拆分数组循环渲染

直接把原始字符串按分隔符拆分为行数组,循环渲染每一行内容,完全规避XSS风险:

<template>
  <b-modal title="内容展示">
    <div v-for="(line, idx) in lineList" :key="idx">
      {{ line }}
    </div>
  </b-modal>
</template>

<script>
export default {
  computed: {
    lineList() {
      return this.actualString.split(" / ")
    }
  }
}
</script>

内容的提问来源于stack exchange,提问作者user16365685

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:36:08