vue.js - 如何渲染基于 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 中。
解决方案
我认为你想要的是插槽。(参见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>
推荐阅读
- google-apps-script - 谷歌表单自动电子邮件
- mysql - 如何在每笔交易的价值旁边显示所有交易的总和
- c# - 为什么 Visual Studio 代码将 C# 正确打印到终端,但不输出?
- anaconda - Mac OS Mojave - 系统 .condarc 文件的位置
- c++ - 'multiline' 不是 'std::__cxx11::regex' 的成员
- tensorflow - Keras:多个输出,只损失一个函数?
- android - 使用 cardview 实现 Checkbox
- acumatica - 在发货发布时填充自定义表
- python - 如何创建具有共享某些属性的外键实例的工厂 - 但该属性在父级上不存在?
- sql - 在 SQL Server 中选择特定日期之前的所有已完成月份