0

How can I use variable array keys for bindings in my custom component? In the following example, title must be 'Title 1 for default settings' if componenttype is set to 'default', 'Title 1 for guest settings' if componenttype is set to 'guest' etc. I tried to interpolate it in several ways, but nothing worked so far. Any hints?

<my-component
    v-for="item in items"
    :id="item.id"
    :title="item['componenttype'].title"     <-- how to interpolate here?
>
</my-component>


...
data() {
   return {
      componenttype: 'default',
      items: [
         { 
            1: {
               default: {
                  title: 'Title 1 for default settings',
               },
               guest: {
                  title: 'Title 1 for guest settings'
               }
            },
            2: {
               default: {
                  title: 'Title 2 for default settings',
               },
               guest: {
                  title: 'Title 2 for guest settings'
               }
            },
         }
      ]
   }
}
...
Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
Dong3000
  • 566
  • 2
  • 7
  • 24

2 Answers2

2

Your array currently contains only one object, with multiple nested objects. It should be:

items: [
            {
               default: {
                  title: 'Title 1 for default settings',
               },
               guest: {
                  title: 'Title 1 for guest settings'
               }
            },
            {
               default: {
                  title: 'Title 2 for default settings',
               },
               guest: {
                  title: 'Title 2 for guest settings'
               }
            }
      ]

With this the following should work:

<my-component v-for="item in items"
    :title="item[componenttype].title"
/>
Igor Moraru
  • 7,089
  • 1
  • 12
  • 24
1

You are making componenttype into a string by doing :title="item['componenttype'].title". Just do :title="item[componenttype].title"

Also check your array syntax, there might be some mistakes there

Marton
  • 55
  • 8