【问题标题】:How to render VueJs component based child node text?如何渲染基于 VueJs 组件的子节点文本?
【发布时间】:2019-10-12 00:50:43
【问题描述】:

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

我正在使用a tool 将文本转换为这样的序列图:

在当前实现中,代码(左侧)是通过调用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 中。

【问题讨论】:

  • @LawrenceCherone 如何实现呢?
  • 添加了更多背景,希望现在更有意义。 @LawrenceCherone

标签: vue.js


【解决方案1】:

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

您的组件代码如下所示:

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

一个可运行的例子

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

<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>

【讨论】:

  • 谢谢,我认为你是对的。但是,我无法使其与 Web 组件一起作为构建目标工作。我在另一个问题中问过这个问题:stackoverflow.com/questions/58353854.
猜你喜欢
  • 1970-01-01
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
  • 2017-09-28
  • 1970-01-01
  • 2018-01-09
  • 1970-01-01
相关资源
最近更新 更多