首页 > 解决方案 > 如何渲染基于 VueJs 组件的子节点文本?

问题描述

======更新了更多背景=====

我正在开发一种将文本转换为序列图的工具,如下所示:在此处输入图像描述

在当前实现中,代码(左侧)是通过调用store.dispatch. 我想让其他项目更容易集成。我想要实现的是创建一个 Web 组件:<sequence-diagram />. 它可以这样使用:

// Format A
<sequence-diagram>
  response = BookController.Get(id)
  ....
</sequence-diagram>

上面的 DOM 元素将被渲染为序列图(如上图右侧所示。

为了使组件正确呈现,它需要知道“代码”是什么。要将代码 ( response = ....) 传递给组件,我知道我可以像这样使用attributes和访问它props

// Format B
<sequence-diagram code="response = ..." />

但是,当代码很长时,上述格式不像将代码作为子节点文本那样可读(想象多行代码)。如果我使用“格式 A”,如何在我的 Web 组件中获取代码内容?

======原来的问题=====

我想要实现的是这样的:

<my-component>
  some text
</my-component>

我已经设法通过使用属性使其工作:

<my-component code="some text" />

在我的情况下,使用子节点文本更具可读性,因为文本可能很长。

在模板中,它已经有一个子组件。当前模板就像

<div> <myChildComponent/> </div>

我不需要将文本保留在结果 dom 中。

标签: vue.js

解决方案


我认为你想要的是插槽。(参见https://vuejs.org/v2/guide/components.html#Content-Distribution-with-Slots)。

您的组件的代码如下所示:

<div>
    <slot></slot>
    <myChildComponent/>
</div>

一个可运行的例子

下面我们有一个组件,它在带有红色背景alert-box的样式中显示错误消息。<div>这是我们使用它的方式:

<alert-box> This email address is already in use. </alert-box>

它会生成如下所示的 HTML:

<div>
    <strong>Error!</strong>
    This email address is already in use.
</div>

看看它的实际效果:

Vue.component('alert-box', {
  template: `
    <div class="demo-alert-box" style="background-color: red; color: white;">
      <strong>Error!</strong>
      <slot></slot>
    </div>
  `
})

new Vue({
  el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <alert-box> This email address is already in use.  </alert-box>
  <p> I'm a normal paragraph. </p>
</div>


推荐阅读