0👍
You could just loop through the array and set the values to true or false depending on whether the item is at the correct index.
selectStudent(id) {
this.selectedStudent = this.students[id]
for (let i= 0; i < this.students.length; i++) {
this.students[i].isSelected = i === id;
}
},
- [Vuejs]-How to make statement with Vue and data from HTML
- [Vuejs]-Vue 3 returns an error after running my project and compiling it with npm run dev
0👍
With generic for you may do this, all students will have their property modified, just check if the student’s key
matches the id parameter.
selectStudent(id) {
this.selectedStudent = this.students[id];
for (let key=0; key<this.students.length; key++) {
this.students[key].isSelected = key === id;
}
}
To test here:
const object = {
students: [
{
name: "Fernanda",
isSelected: false
},
{
name: "Paula",
isSelected: false
},
{
name: "Gabriel",
isSelected: false
}
],
selectedStudent: null,
selectStudent(id) {
this.selectedStudent = this.students[id];
for (let key=0; key<this.students.length; key++) {
this.students[key].isSelected = key === id;
}
}
}
object.selectStudent(1);
console.log(`Selected student: ${object.selectedStudent.name}`);
object.selectStudent(2);
console.log(`New selected student: ${object.selectedStudent.name}`);
console.log(object.students);
- [Vuejs]-I am getting a white empty page when opening this vue view (HTML)
- [Vuejs]-How to build an external configuration file in Vue.js based on your environment
0👍
Working Demo :
const app = new Vue({
el: '#app',
data: {
students: [{
id: 1,
name: 'Student 1',
isSelected: false
}, {
id: 2,
name: 'Student 2',
isSelected: false
}],
studentSelected: false
},
methods: {
selectStudent(event) {
if (event.target.checked) {
this.students.forEach((student) => {
student.isSelected = parseInt(event.target.value) === parseInt(student.id)
})
}
console.log('updated students list : ', this.students)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li v-for="student in students" :key="student.id">
<input type="checkbox" :value="student.id" v-model="student.isSelected" id="student.id" @click="selectStudent">
{{student.name}}
</li>
</ul>
</div>
Source:stackexchange.com