I am building a calendar view of assigned tasks, with an array controlling which tasks should display in each day's cell. I need to reference a varying array key in the v-for loop, but can't find the proper syntax.
My dataset (for tasks on the 5th and 6th of the month) is:
assignments: {
'05':
[
'task one',
'task two'
],
'06':
[
'task three',
'task four'
]
},
This hard-coding to day ['05'] works as I'd like:
<tbody id="calendar-table">
<tr>
<td v-for="(day, index) in calendar.days_array" v-if="index < 7">
<table>
<tr>
{{day}}
</tr>
<tr v-for="task_name in condensedAssignments['05']">
<td>
{{task_name}}
</td>
</tr>
</table>
</td>
</tr>
This gets the attached screenshot: calendar with tasks within all days
I want to replace the '05' in the second loop with the contents of the variable "day" of the first loop. Variations on v-for="task_name in assignments[{{day}}]" are rejected. I've looked into computed properties or methods, but haven't found a way to pass the current iteration's "day" into them.
How do I get the inner loop to recognize the "day" of the outer loop?
CodePudding user response:
You can use the variable name as index for your condensedAssignments variable, but, I think it can't work because the index is a string and the variable day is a number.
You can do this:
<tr v-for="task_name in condensedAssignments[String(day).padStart(1, '0')]">
<td>{{task_name}}</td>
</tr>
String(day) -> Cast variable to a string
.padStart(2, '0') -> Add one zero at left because your index is '05' then two chars long
CodePudding user response:
Actually, you have several problems here.
First, you should not use v-if and v-for on the same element. If you only want the first n elements, a solution could be to use the slice method : calendar.days_array.slice(0, 7)
The second anomaly is that your assignments variable isn't an Array but an Object. You can search how to iterate through an object or check this Digital Ocean tutorial.
Also, you can call the second v-for statement on your variable instead of harcoding your taskname.
It may looks something like this :
<td v-for="(day, key, i) in calendar.days_array">
<tr>{{ key }}</tr>
<tr v-for="task_name in day">
{{ task_name }}
</tr>
</td>
CodePudding user response:
Thank you to fdisotto for the quick answer. I tried again using a method in the meantime, and was reminded that I have another issue: My "day" field is sometimes null. I was able to get it working, though, with this method:
daysTasks: function(day){
if (!day) {return []};
if (String(day).length < 2) {
day = '0' day;
}
return this.assignments[day];
},
and this template:
<td v-for="(day, index) in calendar.days_array" :key='day' v-if="index < 7">
<table>
<tr>
{{day}}
</tr>
<tr v-for="task_name in daysTasks(day)" :key='task_name'>
<td>{{task_name}}
</td>
</tr>
Now, only the 5th of the month sees the first two tasks, and the 6th sees the last two.
