0

I am trying to pass multiple values through Vue.js, under the same key name to keep it dynamic.

This is my code:

Input.vue:

<search-popover :fields="[{
 names: ['Title1', 'value1'],
 names: ['Title2', 'value2'],
}]"></search-popover>

Now, in my Popover.vue file, I only get the last element of the :fields:

<ul v-for="field in fields">
    <li>
       <h5>{{ field.names[0] }}</h5>
       {{ values[field.names[1]]}}
    </li>
</ul>

Will output:

Title2
Value2

How can I do, so I can set the values of :fields dynamically, so I can access the array in my v-for, and it will output:

Title1
Value1

Title2
Value2
5
  • 1
    a syntax problem :fields="[{ names: ['Title1', 'value1'], names: ['Title2', 'value2'], }]", i think you are actually trying to do :fields="[ { names: ['Title1', 'value1'] }, { names: ['Title2', 'value2'] }, ]" Commented Sep 18, 2018 at 14:31
  • I don't think that you can assign two times the same key in a javascript object. const object = { foo: 'one', foo: 'two' } console.log(object) => {foo: 'two'} Commented Sep 18, 2018 at 14:32
  • @Hammerbot Any other way I can dynamically assign multiple values to the component directly? Commented Sep 18, 2018 at 14:33
  • You should try what @JacobGoh wrote: :fields="[ { names: ['Title1', 'value1'] }, { names: ['Title2', 'value2'] }, ]" Commented Sep 18, 2018 at 14:37
  • Ah, didn't see your comment Jacob! This works like a charm. Please submit it as an answer :) Commented Sep 18, 2018 at 14:39

2 Answers 2

1

the problem is in

:fields="[{
 names: ['Title1', 'value1'],
 names: ['Title2', 'value2'],
}]"

where you are creating 1 array containing only 1 object.

(when an object has duplicated properties, the latter one is used. Therefore, { names: ['Title1', 'value1'], names: ['Title2', 'value2'], } is equilavant to { names: ['Title2', 'value2'], })

What you want is probably 1 array containing 2 objects, which should be

:fields="[ 
    { names: ['Title1', 'value1'] }, 
    { names: ['Title2', 'value2'] }, 
]"
Sign up to request clarification or add additional context in comments.

Comments

1

You are not able to have the same key name more than once or the last key will be the only one display.

Correctly iterating through names must be with its own object. Like this:

:fields = "[
  { names: ['Title1', 'value1'] }, 
  { names: ['Title2', 'value2'] }
]"

As written by @jacobgoh

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.