Home  >  Q&A  >  body text

How to get newline character (\n) in Vue 3 slot content?

I'm trying to migrate a Vue 2 component to Vue 3. The idea is like Vue's "ln2br" (actually "ln2p").

so...

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

Should render:

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

This is my working component MyLinebreaker.vue Vue 2 Code:

<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>
The

Slots API changed in Vue 3 so I tried rewriting my lines calculations:

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

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

But it renders wrong (all lines are in one line) because .children does not contain \n characters.

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

So, how to get the text content of \n char in Vue 3?

P粉391677921P粉391677921229 days ago474

reply all(1)I'll reply

  • P粉752479467

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

    Change compilerOptions.whitespace to preserve in Vue, as here is relevant. < /p>

    app.config.compilerOptions.whitespace = 'preserve'
    

    For more details, see the Vue 3 documentation: https://v3.vuejs.org/api/application-config.html#compileroptions-whitespace

    reply
    0
  • Cancelreply