首页  >  问答  >  正文

如何在Vue 3插槽内容中获取换行符(\n)?

我正在尝试将 Vue 2 组件迁移到 Vue 3。这个想法就像 Vue 的“ln2br”(实际上是“ln2p”)。

所以...

<my-linebreaker>
  This is the line 1.
  This is the line 2.
  This is the line 3.
</my-linebreaker>

应该渲染:

<div>
  <p>  This is the line 1.</p>
  <p>  This is the line 2.</p>
  <p>  This is the line 3.</p>
</div>

这是我的工作组件 MyLinebreaker.vueVue 2代码:

<template>
  <div>
    <p v-for="(line, index) in lines" :key="index">{{ line }}</p>
  </div>
</template>

<script>
export default {
  computed: {
    lines () {
      const slot = this.$slots.default
      const text = slot ? slot[0].text : ''

      return text.split('\n')
    }
  }
}
</script>

Slots API 在 Vue 3 中发生了变化,因此我尝试重写我的 lines 计算结果:

<script>
export default {
  computed: {
    lines () {
      const slot = this.$slots.default
      const text = slot ? slot()[0].children : ''

      return text.split('\n')
    }
  }
}
</script>

但它渲染错误(所有行都在一行中),因为 .children 不包含 \n 字符。

<div>
  <p>  This is the line 1. This is the line 2. This is the line 3.</p>
</div>

那么,如何在Vue 3中获取 \n char 的文本内容?

P粉391677921P粉391677921177 天前431

全部回复(1)我来回复

  • P粉752479467

    P粉7524794672024-03-27 10:03:43

    在 Vue 中将 compilerOptions.whitespace 更改为 preserve,如此处相关。< /p>

    app.config.compilerOptions.whitespace = 'preserve'
    

    有关更多详细信息,请参阅 Vue 3 文档:https://v3.vuejs.org/api/application-config.html#compileroptions-whitespace

    回复
    0
  • 取消回复