export default {
data(){
return {
users: [] // async data called in create or mounted hook
}
},
computed: {
filteredUsers() {
return this.users.filter(el => el === 'red')
}
someFunction() {
// 1. this does not work
const result = this.users.filter(el => el === 'red')
console.log(result) // undefined
// 2. this works
console.log(this.filteredUsers)
}
}
}
In the example, #1 is undefined because users is initially empty. Which I understand.
How come I do not have to put a conditional or a check to see if filteredUsers exists when using in another computed? How does Vue handle this logic internally?
As the users array changes, the computed filteredUsers will change. And when this changes I'm assuming the other computed properties will refresh?
I'm fairly new to Vue so curious if there are any caveats to using computed within computed?
You can directly use this.filteredUser() inside your someFunction(). Vue caches the computed property and if the source data changes it cache it again and do not do any computing for the same computed call. Here is a part from Vue document "computed properties are cached based on their reactive dependencies." This is probably why you are having this issue.