I have a description input field which I want to make it as non-required by checking the checkbox (while unchecking it will do the vice versa).
Here are what I have done:
<template>
<tr v-for="(item, i) of $v.timesheet.items.$each.$iter">
<td>
<input type= "checkbox" v-on:click= "check(i)" status="status">
</td>
<td>
<input type="text" placeholder="Description">
</td>
</tr>
<tr>
<td>
<button type="button" @click="itemCount++">Add Item</button>
</td>
</tr>
</template>
<script>
import { required, minLength } from "vuelidate/lib/validators";
export default {
data() {
return {
status: false,
itemCount: 1,
timesheet: { items: [{description: ""}] }
}
},
validations() {
if (this.status == false) {
return{
timesheet: {
items: {
required,
minLength: minLength(1),
$each: { description: { required }},
}
}
}
} else {
return{
timesheet: {
items: {
required,
minLength: minLength(1),
$each: { description: { }}
}
}
}
}
},
watch: {
itemCount(value, oldValue) {
if (value == oldValue) {
return;
}
if (value > oldValue) {
for (let i = 0; i < value - oldValue; i++) {
this.timesheet.items.push({
description: ""
});
}
} else {
this.timesheet.items.splice(value);
}
}
},
methods: {
check(index){
this.status = !this.status;
}
}
}
</script>
This toggles all rows at once instead of working at the only intended individual row.
How do I fix the toggling so that it works just at that specific row?
If you need to track a value per row, then that value needs to be kept with each individual item that is rendering the row.
Then, if you pass the event and the index (or a unique id), you can update your data in the method with the new value.
<template>
<div class="hello">
<h1>Result</h1>
<ul>
<li v-for="(person, i) in persons" :key="i">
<label
>name:
<input :value="person.name" @change="changeName($event, i)" />
</label>
<label>
status:
<input
type="checkbox"
:checked="person.status"
@change="check($event, i)"
/>
</label>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
persons: [
{ name: "Karl", status: false },
{ name: "Irma", status: true },
{ name: "David", status: false },
],
};
},
methods: {
check(event, index) {
this.persons[index].status = event.target.value === "on";
},
changeName(event, index) {
this.persons[index].name = event.target.value;
},
},
};
</script>