Search code examples
arraysvue.jsstring-interpolationarray-key

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


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

Solution

  • 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"
    />