How to get newline character (\n) in Vue 3 slot content?
P粉391677921
P粉391677921 2024-03-26 12:42:18
0
1
497

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粉391677921
P粉391677921

reply all(1)
P粉752479467

Change compilerOptions.whitespace to preserve in Vue, as here is relevant.

app.config.compilerOptions.whitespace = 'preserve'

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template