I want to use a counter flag in v-for inside another v-for loop for counting total run of inside loop.
Here is my template:
<a :href="'#/product/'+list.id" :id="ikeyCounter" v-for="item,ikey in section.list" class="movie item fcosuable">
{{ ikeyCounterPlus() }}
<div class="verticalImage">
<div class="loader hideloading"></div>
<img :src="item.thumb" alt="">
</div>
</a>
data() {
return {
loading: true,
status: null,
list: [],
sections: null,
ikeyCounter: 3
}
},
And method:
ikeyCounterPlus() {
this.ikeyCounter++;
},
but I'm getting wrong result on ikeyCounter variable. Id of a tag started from "15003" to "15150", if I don't call ikeyCounterPlus() inside v-for tag, for loop will run correctly (150 run)
If you want to count your objects, then just count your data. No need to involve DOM.
section.list is an array, so section.list.length should give you desired count.
Also, as mentioned in the answer before, use some unique property of item (for example some sort of id) as the value for :key attribute.
You can't do it like this, Vue.js is reactive framework and you should learn a little bit before asking these kind of questions - https://v2.vuejs.org/v2/guide/reactivity.html
Use your key as id instead
Related
AFAIK, first shown here by Vladimir Milosevic
<div
v-for="( id, index, user=usersData[id], doubleId=doubleThat(id) ) in users"
:key="id">
{{ user.name }}, {{ user.age }} years old And DoubleId = {{ doubleId }}
</div>
I expanded his codepen. Looks like you can define several variables local to the loop this way.
Are there any side-effects or risks you see with this technique?
I find this way to be the most convenient and clean out there but since that is apparently not the intended use it may not be future-proof.
EDIT:
Here is another pen which demonstrates the use case better. While here we reference just one computed property in one place, if the number of properties and references grows, it will lead to a verbose code.
In general, I think the clean way to do what you want to do is to bring the data into a format, where you can loop over it without extra steps. This way, you will never need those additional variables in v-for.
The example from your codepen could look like this:
const app = new Vue({
el: '#app',
data: {
years: [2024, 2025, 2120],
usersData: {...}
},
computed: {
// user objects for each year
ageData() {
return Object.fromEntries(this.years.map(year => [year,
Object.values(this.usersData).map(user => this.userInYear(user, year))
] ))
}
},
methods: {
userInYear(user, year){
return {...user, age: user.age + (year - 2023)}
}
},
});
Now you can iterate it without interruption and shenanigans:
<div v-for="(users, year) in ageData" :key="year">
<b>In {{ year }}:</b>
<div v-for="user in users" :key="user.name">
{{ user.name }} will be {{ user.age }} years old.
</div>
</div>
It is easier to read and change, and it has the added benefit that you can inspect ageData in the console.
That said, I think it is very interesting that you can declare additional variables in v-for, I assume it is possible because of the way vue parses and builds expressions from the provided string, I am pretty sure it won't be removed, and if you and the people you work with are comfortable with it (and are prepared to hear the above over and over like just now), by all means, go for it.
I have the following Problem:
I'm using Ionic Vue and a VueX Store to save my data from an API.
Now I have set an array, which contains the IDs of entries, which shall be checked or unchecked.
Since I should not modify the API-Model class, I have saved the IDs of checked entries in a seperate Array in my VueX Store, which I update as needed.
Now I'm trying to make the checkboxes checked / unchecked depending on that array.
I tried it by adding v-model = "checkedVehicles.included(vehicle.vehicle_id)", but all I get is an Error:
'v-model' directives require the attribute value which is valid as LHS vue/valid-v-model
Heres the Part whit the checkboxes, hope that is all you need :)
<IonItem v-for="vehicle in vehicleList" v-bind:key="vehicle.vehicle_id">
<IonLabel>
<h2>{{ vehicle.manufacturer }} {{ vehicle.model }}</h2>
<p>{{ vehicle.display_name }}</p></IonLabel>
<IonCheckbox slot="end"
v-model="checkedVehicles.includes(vehicle.vehicle_id)"
#click="checkIfAllDeselected"
#update="this.updateCheckboxOnClick(vehicle.vehicle_id)"/>
</IonItem>
The checkedVehicles Arrays is intialized as String[].
Also tried to use a function, which returns true or false, depending on the checkedVehicles Array has the ID included or not, but that also gives the same error
The other functions, which add or remove entires to the correspondig arrays are working fine, already checked that. only the Checkboxes are not working as intended.
Has anyone a clue, what I'm doing wrong?
This is obvious because we can't evaluate a condition in v-model. We generally bind a variable to the v-model.
For eg:
Consider you have a attr called vehicle in data.
data() {
return {
Vehicle list: [{
checked: true,
manufacturer: '',
display_name: '',
vehicle_id: ''
},
{
checked: true,
manufacturer: '',
display_name: '',
vehicle_id: ''
},
]
}
then you can bind it as
<IonItem v-for="vehicle in vehicleList" v-bind:key="vehicle.vehicle_id">
<IonLabel>
<h2>{{ vehicle.manufacturer }} {{ vehicle.model }}</h2>
<p>{{ vehicle.display_name }}</p></IonLabel>
<IonCheckbox slot="end"
v-model="vehicle.checked"
#click="checkIfAllDeselected"
#update="this.updateCheckboxOnClick(vehicle.vehicle_id)"/>
</IonItem>
To conclude, variables that can hold value can only be used in v-model
I am building an app using Node.js and Vue.
My DATA for the component is the following:
data() {
return {
campaign: {
buses: [],
weeks: [
{
oneWayBuses: [],
returnBuses: []
}
]
},
busesMap: {
// id is the bus ID. Value is the index in the campaign.buses array.
},
};
},
I fill the buses and weeks array in MOUNTED section in two separate methods after getting the data from the server:
responseForWeeks => {
responseForWeeks.forEach(
week => this.campaign.weeks.push(week);
)
}
responseForBuses => {
responseForBuses.forEach(
bus => this.campaign.buses.push(bus);
// Here I also fill the busesMap to link each week to its bus index in the array of buses
this.busesMap[bus.id] = this.campaign.buses.length - 1;
)
}
So the idea is that my busesMap looks like busesId keys and index values:
busesMap = {
'k3jbjdlkk': 0,
'xjkxh834b': 1,
'hkf37sndd': 2
}
However, when I try to iterate over weeks, v-if does not update so no bus info is shown:
<ul>
<li
v-for="(busId, index) in week.oneWayBuses"
:key="index"
:item="busId"
>
<span v-if="campaign.buses[busesMap.busId]">
<strong>{{ campaign.buses[busesMap.busId].busLabel }}</strong>
leaves on the
<span>{{ campaign.buses[busesMap.busId].oneWayDepartureDate.toDate() | formatDate }}</span>
</span>
</li>
</ul>
On the other side, if I shorten the v-if condition to campaign.buses, then I get into the condition but campaign.buses[busesMap.busId] is still undefined, so I get an ERROR trying to display busLabel and oneWayDepartureDate
I've read vue in depth documentation, but couldn't come up with a resolution.
Any gotchas you can find out?
Try this:
async mounted(){
await responseForWeeks
await responseForBuses
responseForWeeks => {
responseForWeeks.forEach(
week => this.campaign.weeks.push(week);
)
}
// this is partial since it is what you provided
responseForBuses => {
responseForBuses.forEach(
bus => this.campaign.buses.push(bus);
// Here I also fill the busesMap to link each week to its bus index in the array of buses
this.busesMap[bus.id] = this.campaign.buses.length - 1;
)
}
}
Basically you want to make sure that before your component loads your data is in place. You can also create computed properties which will force re rendering if dependencies are changed and they are in the dom.
Actually, the problem was indeed in the HTML.
When trying to access the object keys, better use [] intead of a dot .
Final HTML result would be as follows:
<ul>
<li
v-for="(busId, index) in week.oneWayBuses"
:key="index"
:item="busId"
>
<span v-if="campaign.buses[[busesMap[busId]]]">
<strong>{{ campaign.buses[busesMap[busId]].busLabel }}</strong>
leaves on the
<span>{{ campaign.buses[busesMap[busId]].oneWayDepartureDate.toDate() | formatDate }}</span>
</span>
</li>
</ul>
What was happening is that previously campaign.buses[busesMap.busId] did not exist, thus not rendering anything. Solved to campaign.buses[busesMap[busId]]. Also used claudators for the displayed moustache sintach.
Hope it helps someone else messing with Objects!
I'm trying to get object items from inside a parent object using a v-for inside another v-for in Vue.js.
Data structure:
flights: [
{
"airline": "BA",
"airport": "EBJ",
"status": {
"_code": "A",
"_time": "2018-03-02T14:19:00Z"
}
},
etc....
]
<div v-for="flight in flights">
<p>{{flight.airline}}</p>
<p>{{flight.airport}}</p>
<div v-for="st in flight.status">
<p>{{st._code}}</p> // should return 'A'
<p>{{st._time}}</p> // should return '2018-03-02T14:19:00Z'
</div>
</div>
However, neither st._code or st._time return anything. st returns both values ("A" and "2018-03-02T14:19:00Z").
Any idea on how to return the single values inside the status object?
It is possible to use v-for on an object, as you're trying to do with status, but the syntax is slightly different; in cases where iterating over an object is useful you'll generally want to include the key as well as the value:
<div v-for="(val, key) in flight.status">
<p>{{key}}: {{val}}</p>
</div>
would output
<p>_code: A</p>
<p>_time: 2018-03-02T14:19:00Z</p>
In your case you already know the specific keys you want, so it would be easier to not use v-for and instead just use e.g {{flight.status._code}}.
Unless there can be more than one "status" per flight, there's no good reason to wrap status in an array. This will work with your existing data structure:
<div v-for="flight in flights">
<p>{{flight.airline}}</p>
<p>{{flight.airport}}</p>
<p>{{flight.status._code}}</p>
<p>{{flight.status._time}}</p>
</div>
The reason you are not seeing the expected output is because, of this line:
<div v-for="st in flight.status">
That means you are expecting vue to iterated throught this:
"status": {
"_code": "A",
"_time": "2018-03-02T14:19:00Z"
}
and the above is an object, not an array ... so unless status is an array, it won't work.
If you expect your code to work, try changing your array to this:
flights: [
{
"airline": "BA",
"airport": "EBJ",
status: [{
"_code": "A",
"_time" : "2018-03-02T14:19:00Z"
}]
}
]
working demo:
https://jsfiddle.net/943bx5px/82/
Here's the markup:
<ul>
<li v-for="(topic,label,index) in guides" :key="index">
<ul>
<strong> {{label}} </strong>
<li v-for="rule in topic">
{{rule.val}},
{{Object.keys(topic)[0]}}
</li>
</ul>
</li>
And here's the data for this list:
data: {
guides: {
"CSS" : {
1502983185472 : {
"modifiedby" : "bkokot",
"val" : "When adding new rule, use classes instead of ID whenever possible"
},
1502983192513 : {
"modifiedby" : "bkokot",
"val" : "Some other rule"
},
},
"Other" : {
1502628612513 : {
"modifiedby" : "dleon",
"val" : "Some test text"
},
1502982934236 : {
"modifiedby" : "bkokot",
"val" : "Another version of text"
},
}
}
}
So as you can see there is a "guides" property which is an object of other objects that do have inner objects too.
All I want is to get the keys from inner (second) loop (numbers "1502983185472" etc).
The only solution that i see right now is "Object.keys(topic)[0]", but is there a more accurate alternative in vuejs for this?
Adding key, index parameters to the second loop(with new unique variable names) doesn't work for me.
Here's a working fiddle: https://jsfiddle.net/thyla/yeuahvkc/1/
Please share your thoughts.
If there is no good solution for this - may it be a nice topic for a feature request in Vuejs repo(unless I'm missing something terrible here)?
Generally if you're curious - that number is a momentjs timestamp - I'm using this data in firebase, and saving initial timestamp as an object key seemed to be a pretty nice solution (since we need a key anyway, to save some space - I can use this key instead of another extra timestamp property in my object, this also makes the instance very 'targetable' in firebase).
Thank you in advance ! Cheers!
p.s: another possible solution is converting inner loop (css, other) from objects into arrays and using time-stamp as another object property, but I'm using firebase - saving this data as an object gives me an ability to quickly access some instance without parsing the entire parent object/array, makes it more easy to filter, search, reupdate, etc - thus converting object into array is not a good solution for instance with very large number of items.
Your fiddle renders the number key of the first entry of a topic for each of the rules in that topic. I'm assuming you want to actually show the number key for each corresponding rule.
That value is passed as the second parameter in the v-for:
<li v-for="(rule, ruleID) in topic">
{{ rule.val }},
{{ ruleID }}
</li>
Here's a working fiddle.
Here's the documentation on using v-for with an object.
This can be solved by as follows in the second loop like
<li v-for="(rule,index) in topic">
{{rule.val}},
{{index}}
</li>
Please refer this fiddle => https://jsfiddle.net/yeuahvkc/7/
Use explicit definitions
Other answers use ".val", but it's not clear where that originates.
Instead, just declare everything, like:
<li v-for="(value, key, index) in rule">
{{key}}: {{value}} - {{index}}
</li>