0
votes

Some trouble with saving some array that uses a main-array, but is added to another object.

I have a list of distances (array of numbers).

<ul>
    <li v-for="(distance, index) in distances">
        <a>{{ distance }} km</a>
    </li>
</ul>

And the same view I can add some new distances

<input type="number" v-model="newDistance" /><button @click="addDistance(newDistance)">+</button>

This works, the distances are added to the array when added. After adding the distance to the ul-list, I also want to add the distances to the checkboxes of each Car that is inside an other array.

<article v-for="car in cars">
    <div v-for="(distance, index) in distances">
        <div @click="updateCar(car, product.distances)">
            <input :id="car.slug+index" :name="car.slug" type="checkbox" :checked="checkDistances(surface, car)" />
            <label :for="car.slug+index">{{ distance }} km</label>
        </div>
    </div>
</article>

The working Functions:

checkDistances(distance, car) {
    var self = this;
    if(typeof car.distances === 'object') {
        if(typeof car.distances[self.form.slug] !== 'undefined') {
            return (car.distances[self.form.slug].includes(distance))
        }
    }
    return false;
},

And the function to add distances:

addDistance(newDistance) {
    this.distances.push(parseInt(newDistance));
},

This is the UpdateCar function

updateCar(car, distances) {
    console.log(this.distances);
    console.log(distances);
},

Both console logs show the same array. It all returns always ALL items the are in the 'distances' array and not only the selected input fields..

What I want, is that I can update a car when checking a checkbox, so it'll return only the distances that are selected.

1

1 Answers

0
votes

It seems like you're just toggling the checkboxes on and off based on the result of checkDistances, but not storing them anywhere. The organization of your example isn't 100% clear to me, but you probably want something along these lines:

// In your template
<input
    :id="car.slug+index"
    :name="car.slug"
    type="checkbox"
    :checked="distance in car.distances"
    @click="addDistanceToCar(distance, car)" />

// In your methods:
addDistanceToCar(distance, car) {
    car.distances.push(distance)
}