【问题标题】:Elegant way to use dynamic components with props in Vue在 Vue 中使用带有 props 的动态组件的优雅方式
【发布时间】:2022-01-03 18:47:17
【问题描述】:

以下案例:我有一个 API 输出我的页面的所有内容,以及它的结构等(为了更好地理解,想象一个包含页面构建器的 CMS,作者可以通过拖动来放置组件并 drop 生成页面内容,由该 api 传递到前端)。

api 输出的结构类似于:

{content: [
  {component: hero, content: {...} },
  {component: form, content: {...} },
  ...
]}

所以要生成相关内容,我会考虑使用动态组件,例如:

<template v-for="item in content">
  <component :is="item.component" />
</template>

但是,这样做我会遇到一个问题,即我必须以某种方式将属性数据添加到我的组件中,这(据我所知)在 Vue 文档中没有描述。所以现在我想知道如何将道具传递给具有完全不同道具的动态组件(英雄可能有图像,表单可能有输入占位符等等) - 有什么想法吗???

【问题讨论】:

  • 道具通过 v-bind 传递,就像任何其他动态道具一样。

标签: javascript api vue.js v-for vue-dynamic-components


【解决方案1】:

现在有必要说明您使用的是哪个版本的 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>

【讨论】:

  • 只有当一个人可以控制数据结构时才有效 - 否则会有一个警告,一个人只能将一个数据对象放入一个组件中,因此一个组件只能有一个单一的道具。现在在我看来,这是解决问题的唯一方法。 : /
  • @IrgendSonHansel ?抱歉,但我并没有真正理解您所说的约束。您可以传入任意数量的对象:作为Array 或将其传播到新的Object 中。 sn-p 中的两个动态组件都接受多个道具。
【解决方案2】:

看看v-bindhttps://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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-27
    • 2020-07-02
    • 2020-09-16
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    相关资源
    最近更新 更多