2👍
✅
Your search result set should really be an array (of result objects).
Something like:
[
{"id": 1, "text": "foo"},
{"id": 2, "text": "bar"},
{"id": 3, "text": "baz"},
...
]
Or, more elegant:
{
"searchterm": "input value"
"total_results": 31,
"limit": 10,
"page": 2,
"results": [
{"id": 1, "text": "foo"},
{"id": 2, "text": "bar"},
{"id": 3, "text": "baz"},
...
]
}
Then, the computed should be as simple as:
data() {
return {
results: []
}
},
computed: {
resultsToShow() {
return this.results.slice(0, 6)
}
},
methods:{
fetchResults() {
axios.post('includes/searchproducts_json.php', {
// Post data, add value of input to searchterm
searchterm: this.$refs.searchterm.value
})
.then((response) => {
if (response.status === 200 && response.data.length) {
this.results = response.data
}
})
.catch(console.error)
}
}
See a working demo: https://codesandbox.io/s/thirsty-germain-i6w4w?file=/src/App.vue
And because it’s just a simple slice
, you could even remove (the overhead of) the computed property and just write it into the template inline expression:
<ol>
<li v-for="(result, index) in results.slice(0, 6)" :key="index">
{{ result.text }}
</li>
</ol>
1👍
Object.keys() returns an array of the object keys, which could be the thing you are looking for if i understand correctly. Then you could create a computed property something like this:
test() {
return Object.keys(this.responseData).map((key) => this.responseData[key]).slice(0,6);
}
This transforms the object to an an array after which you can use a simple slice method to get the first 6 elements.
Source:stackexchange.com