In my Vue application, I have a very small line of code based on a v-for loop and it works until I throw a V-IF into it.
THe following works:
<div v-for="date in dates" :key="date">
<th v-for="store in stores">@{{store.stock}}</th>
</div>
However, when I try to get it to only show that value if the date in the object matches the dates object, I get that store is undefined
<div v-for="date in dates" :key="date">
<div v-for="store in stores">
<th v-if="store.date === date">@{{store.stock}}</th>
</div>
</div>
Here are my objects:
stores: [
{
store: "123",
date: "2021-09-01",
stock: "145"
}
]
dates: [
{
date: "2021-09-01"
}
]
Why am I having such an issue when trying to match the dates in the v-if?
You made a little mistake. date should be date.date!
<div v-for="date in dates" :key="date">
<div v-for="store in stores">
<th v-if="store.date === date.date">@{{store.stock}}</th>
</div>
</div>
instead of use v-if with v-for you can use computed to get store you need display and then use just one v-for
<template>
<div>
<div
v-for="store in activeStore"
:key="store.stock"
>
{{ store.date }}
</div>
</div>
</template>
<script>
export default ({
data() {
return {
count: 1110,
stores: [{
store: 'test',
date: '2021-09-01',
stock: '145'
}, {
store: 'test',
date: '2021-09-02',
stock: '146'
}, {
store: 'test',
date: '2021-09-03',
stock: '147'
}, {
store: 'test',
date: '2021-09-04',
stock: '148'
}],
dates: ['2021-09-01', '2021-09-02', '2021-09-03', '2021-09-00']
}
},
computed: {
activeStore: function() {
return this.stores.filter((store) => {
if (this.dates.includes(store.date)) {
return store
}
})
}
}
})
</script>
Here is a simple solution using computed property
<div v-for="date in dates" :key="date">
<div v-for="(store, indexer) in getFilteredStores(date)" :key="indexer">
<th>@{{store.stock}}</th>
</div>
</div>
and in your computed, define the below handler to get the store for particular dates
computed: {
getFilteredStores() {
return targetDate => { // targetDate is the argument passed to the handler
return this.stores.filter(store => store.date === targetDate);
}
}
}