How to get line break char (\n) in Vue 3 slots content?
I am trying to migrate a Vue 2 component to Vue 3. The idea is like a "ln2br" ("ln2p" actually) for Vue.
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 the Vue 2 code of my working component MyLinebreaker.vue
:
<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 had changes in Vue 3, so I am trying to rewrite my lines
computed to:
<script>
export default {
computed: {
lines () {
const slot = this.$slots.default
const text = slot ? slot()[0].children : ''
return text.split('\n')
}
}
}
</script>
But it is rendering wrong (all lines in one) because .children
does not contain the \n
char.
<div>
<p> This is the line 1. This is the line 2. This is the line 3.</p>
</div>
So, how can I get the text content with \n
char in Vue 3?
Change the compilerOptions.whitespace
to preserve
in Vue, as related here.
app.config.compilerOptions.whitespace = 'preserve'
See Vue 3 docs for more details: https://v3.vuejs.org/api/application-config.html#compileroptions-whitespace