So I have a Vue page where I'm looping through a few items and I have the following code:
<div v-if="behavior !== 'selected' && filterItems.length >= 5"></div>
<div v-for="(itemName, index) in filterItems" :key="index">[stuff]</div>
Basically I'm looping through some items from an API, but I also want to conditionally show an element if there's 5 or more of those items, otherwise I want it hidden. That element needs to exist outside the loop, but it needs to check how many items are in the loop.
Interestingly enough, the above code works, but it also throws console errors, presumably because I'm accessing "filterItems" outside of the loop itself.
(here's the console error: [Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined")
Any ideas on how I can avoid throwing these errors and accomplish what I need in as vue-native a way as possible?
As requested, here's the code declaring filterItems
. It's just a prop declared as an array:
props: {
filterItems: Array,
behavior: String,
},
It's being passed in from a parent component as an array.
UPDATE: A POSSIBLE SOLUTION?
So I don't know if this is the best way to do this or not, but I was able to get the desired result by doing the following. I'd love to hear feedback on if this is a satisfactory solution:
I added a data value:
data() {
return {
displaySearch: false,
};
},
Then added:
updated() {
if (this.behavior !== 'selected' && this.filterItems.length >= 5) {
this.displaySearch = true;
}
},
Then ran a check against the new boolean: v-if="displaySearch"
My thinking is that the check run against displaySearch
after the page renders and it avoids the TypeError. I tried mounting it, intially and it broke immediately.
Final Solution See the answer below from Stephen Thomas. I settled on this as it appears to me to be the simplest and most elegant answer.
presumably because I'm accessing "filterItems" outside of the loop itself.
Nope. filterItems
is not defined by the v-for
loop. It's defined (or it should be defined) in the component's props
object. As such, it's completely accessible anywhere in your template.
TypeError: Cannot read property 'length' of undefined"
That indicates that filterItems
isn't defined. The parent that includes this component isn't providing a value. You can define a default (empty) array for the property:
props: {
filterItems: {
type: Array,
default() {
return [];
}
},
behavior: String
}
or you can fix the parent