Vue: How to use variable as array key in component binding

1.3k views Asked by At

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'
               }
            },
         }
      ]
   }
}
...
2

There are 2 answers

0
Igor Moraru On BEST ANSWER

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"
/>
0
Marton On

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