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'
               }
            },
         }
      ]
   }
}
...
1
  • You have two default inside items. How to know which one you need? Commented May 30, 2020 at 18:01

2 Answers 2

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"
/>
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.