[英]Elegant way to use dynamic components with props in Vue
以下案例:我有一个 API 输出我的页面的所有内容,以及它的结构等(为了更好地理解,成像一个包含页面构建器的 CMS,作者可以通过拖放将组件放置到生成页面内容,由该api传递到前端)。
api output 的结构如下所示:
{content: [
{component: hero, content: {...} },
{component: form, content: {...} },
...
]}
因此,要生成相关内容,我会考虑使用动态组件,例如:
<template v-for="item in content">
<component :is="item.component" />
</template>
但是,这样做我会面临一个问题,即我必须以某种方式将属性数据添加到我的组件中,这(据我所知)在 Vue 文档中没有描述。 所以现在我想知道如何将道具传递给具有完全不同道具的动态组件(英雄可能有一个图像,表单可能有输入占位符,等等) - 任何想法?
现在有必要 state 你使用什么版本的 Vue。
使用 Vue 2,您可以这样做:
Vue.component('FirstComponent', { props: ['title', 'prop1_1'], template: ` <div> {{ title }}<br /> {{ prop1_1 }} </div> ` }) Vue.component('SecondComponent', { props: ['title', 'prop2_1', 'prop2_2'], template: ` <div> {{ title }}<br /> {{ prop2_1 }}<br /> {{ prop2_1 }} </div> ` }) new Vue({ el: "#app", data() { return { items: [ { component: 'FirstComponent', props: { title: 'First component title', prop1_1: 'this is prop 1_1' }, }, { component: 'SecondComponent', props: { title: 'Second component title', prop2_1: 'this is prop 2_1', prop2_2: 'this is prop 2_2', }, }, ] } }, template: ` <div> <component v-for="(item, idx) in items":key="idx":is="item.component" v-bind="item.props" ></component> </div> ` })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"></div>
看看v-bind
https://v2.vuejs.org/v2/guide/components-props.html#Passing-the-Properties-of-an-Object (与 Vue 3 相同)。
假设您的 API 包含每个组件的props
属性,那么您可以这样做:
<component v-for="item in content" :is="item.component" v-bind="item.props"></component>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.