如何在Vue 3插槽内容中获取换行符(\n)?
P粉391677921
P粉391677921 2024-03-26 12:42:18
[Vue.js讨论组]

我正在尝试将 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粉391677921
P粉391677921

全部回复(1)
P粉752479467

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

app.config.compilerOptions.whitespace = 'preserve'

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号