[英]Vue.js Interfaces for Components
我目前正在开发一个 vue.js 项目,在那里我得到一个 json 响应,其结构如下:
"fields":
[
{
"type": "A",
"propsA": "foo"
},
{
"type": "A",
"propsA": "foo"
},
{
"type": "B",
"propsB": "bar"
},
{
"type": "C",
"propsC": "bla"
},
]
我的系统应该能够识别字段中的每种类型,然后为它们的属性显示特定的显示。 这应该通过为每种类型使用 Vue.js-Component 来完成。
经过一番研究,我遇到了以下问题:我想创建一种可以动态加载这些组件的方法; 如果在响应中有一个带有"type": "C" ...
加载所述组件并将数据写入模板。
以前是否有人面临过类似的挑战,并且愿意与我分享这可以与我合作的方式?
希望这可以为可能的策略提供一些见解。 我建议全局注册每个可能的组件(或在您认为将使用它们的任何地方)并使用:is
特殊属性来动态加载组件。
注册组件后,您可以遍历传入字段列表,将:is
属性设置为类型,并将属性设置为所有其他传入信息。 这将导致为正确的组件提供其相应的信息。
const A = { props: ['data'], template: ` <div> <p>This is coming from the A component</p> <p>{{ data.text }}</p> </div> ` } const B = { props: ['data'], template: ` <div> <p>This is coming from the B component</p> <p>{{ data.text }}</p> </div> ` } const C = { props: ['data'], template: ` <div> <p>This is coming from the C component</p> <p>{{ data.text }}</p> </div> ` } new Vue({ el: "#app", components: { 'A': A, 'B': B, 'C': C }, data: { fields: [{ type: "A", data: { text: "This is coming from the A data!" } }, { type: "A", data: { text: "This is coming from the A data!" } }, { type: "B", data: { text: "This is coming from the B data!" } }, { type: "C", data: { text: "This is coming from the C data" } }] } })
<script src="https://unpkg.com/vue"></script> <script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script> <div id="app"> <div v-for="(item, key) in fields" :is="item.type" :data="item.data" :key="key" ></div> </div>
让我知道我是否遗漏了任何内容,或者您是否需要进一步解释。
现在我看看其他属性是如何提供的,您可能只发送整个对象,而不是发送包含非类型信息的特定对象。
fields: [{
type: "A",
textA: "This is coming from the A data!"
}, {
type: "A",
textA: "This is coming from the A data!"
}, {
type: "B",
textB: "This is coming from the B data!"
}, {
type: "C",
textC: "This is coming from the C data!"
}]
<div
v-for="(item, key) in fields"
:key="key"
:is="item.type"
:data="item"
></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.