Vue.js / Algolia - Dynamically pass field names in template

126 Views Asked by At

I am trying to dynamically show search results from Algolia, based on an array of names.

Input.vue:

<search-results title="Books" :fields="['booking_reference','shipment_reference']"></search-results>

Results.vue:

<template slot-scope="{ result }">
     <h1 v-for="field in fields">{{ result.field }}</h1>
</template>

However, above code does not return anything in my template. It's just blank.

But my fields array does indeed have values:

enter image description here

And I can see the results from Algolia as well:

enter image description here

But it does not show the results.

If I edit the code and hardcode the field name I want to show, like this:

<template slot-scope="{ result }">
          {{ result.booking_reference }}
</template>

I can see the result just fine in my template.

What am I doing wrong?

Update:

How can I do this with a multidimensional array?

My array:

fields:Array[2]
0:Object
maintitle:"booking_reference"
1:Object
subtitle:"shipment_reference"

I need to be able to access it like:

result.maintitle.field

1

There are 1 best solutions below

2
On BEST ANSWER

try

 <h1 v-for="field in fields">{{ result[field] }}</h1>

instead of

 <h1 v-for="field in fields">{{ result.field }}</h1>