user3714932
user3714932

Reputation: 1353

Vue for loop returning one value

I'm getting an array of contractors from the database. I want it such that when the salary of one contractor is accepted, then the remaining contractors are removed from the DOM.

<div v-for="contractor in contacted_contractors" :key="contractor.id">

    <form @submit.prevent="acceptSalary(contractor.user_id, contractor.maintenance_id)">
       <button>Accept salary</button>
    </form>

</div>

This is the method that attempts to get rid of the remaining contractors after the salary of one has been accepted

  async acceptSalary (user_id, maintenance_id) {
            this.accept_salary.maintenance_id = maintenance_id;
            this.accept_salary.user_id = user_id;
            await axios.post('/api/maintenances/respond/budget', this.accept_salary).then(response => {
                    this.salary_accepted = true

                    for (let i = 0; i < this.contacted_contractors.length; i++) {
                        if(this.contacted_contractors[i].user_id == this.accept_salary.user_id){

                        this.show_contractor = true
                        }

                        else{
                        this.show_contractor = false

                        }
                    return this.show_contractor
                    }

        })
        .catch(error => {})
        }

The problem is that when I run the show_contractor in the HTML it returns the same value for all the contractors, And I want it to return true for the contractor whose salary has been accepted and false for all the others.

<div v-for="contractor in contacted_contractors" :key="contractor.id">
    {{ show_contractor }}
    <form @submit.prevent="acceptSalary(contractor.user_id, contractor.maintenance_id)">
       <button>Accept salary</button>
    </form>

</div>

Upvotes: 0

Views: 112

Answers (1)

Dylan Landry
Dylan Landry

Reputation: 1290

If I understand, it seems that show_contractor is a data property of your vue component that contains this v-for which renders contractors. It's not scoped to single contractors, so it's the same value for all of them.

Like @rguttersohn commented, I recommend a computed property which filters your list of contractors.

<div v-for="contractor in accepted_contractors">
  {{contractor}}
</div>
accepted_contractors() {
  return this.contacted_contractors.filter(contractor => {
    return contractor.user_id === this.accept_salary.user_id
  })
}

Upvotes: 1

Related Questions