简体   繁体   English

如何将动态道具绑定到VueJS 2中的动态组件

[英]How to bind dynamic props to dynamic components in VueJS 2

I'd like to know how I can iterate a list of component names (which come from an AJAX call to an API server) and render them as components, and pass relevant properties to each component (ie bind their properties dynamically). 我想知道如何迭代组件名称列表(来自对API服务器的AJAX调用)并将它们呈现为组件,并将相关属性传递给每个组件(即动态绑定它们的属性)。

So far I have managed to iterate a JSON list of items that represent components, and successfully render these components. 到目前为止,我已设法迭代表示组件的JSON项列表,并成功呈现这些组件。 What I'd like to do now is bind the properties for each component using v-bind . 我现在要做的是使用v-bind每个组件的属性。

In the example below, the item-one component would receive the image property with the item1.jpg value; 在下面的示例中, item-one组件将接收带有item1.jpg值的image属性; and the item-two component wouldn't receive any properties. 并且第二item-two组件不会收到任何属性。

<template>
  <div v-for="item in items">
    <component :is="Object.keys(item)[0]" :v-bind="???"></component>
  </div>
</template>

<script>
  import ItemOne from '../components/item-one'
  import ItemTwo from '../components/item-two'

  export default {
    components: {
      ItemOne,
      ItemTwo
    },
    asyncData () {
      return {
        items: [
          { 'item-one': { 'image': 'item1.jpg' } },
          { 'item-two': { } }
        ]
      }
    }
  }
</script>

I tried using :v-bind="Object.values(Object.keys(item)[0])" but I get the attribute v-bind="[object Object]" in the rendered element. 我尝试使用:v-bind="Object.values(Object.keys(item)[0])"但我在渲染元素中得到属性v-bind="[object Object]"

First, you need to get rid of the colon before v-bind . 首先,你需要在v-bind之前摆脱冒号。 The colon is a short-hand for v-bind when prefixed to an attribute. 当前缀为属性时,冒号是v-bind的简写。 But, when passing an object of key pairs to bind, you simply use the v-bind directive. 但是,在传递密钥对的对象时,只需使用v-bind指令即可。

Second, you are not correctly referencing the properties of each item. 其次,您没有正确引用每个项目的属性。 You can reference them like this: 你可以像这样引用它们:

v-bind="item[Object.keys(item)[0]]"

You wouldn't need to use Object.keys if you changed the structure of your items property a bit: 如果您稍微更改了items属性的结构,则不需要使用Object.keys

items: [{ 
  type: 'item-one', 
  props: { 'image': 'item1.jpg' },
}, {
  type: 'item-two',
}]

This way, by explicitly labeling the component type and properties beforehand, your template would be much easier to understand: 这样,通过事先明确标记组件类型和属性,您的模板将更容易理解:

<div v-for="item in items">
  <component :is="item.type" v-bind="item.props"></component>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM