我正在尝试将 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.vue 的Vue 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 的文本内容?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
在 Vue 中将
compilerOptions.whitespace更改为preserve,如此处相关。有关更多详细信息,请参阅 Vue 3 文档:https://v3.vuejs.org/api/application-config.html#compileroptions-whitespace