简体   繁体   中英

Vue JS How to set option as selected based on passed nested v-for value?

I have a nested v-for inside of another v-for in my Vue project. I'm successfully grabbing correct data; however, I'm trying to use a select dropdown to populate a field and automatically grab the selected option based on the value that would normally work fine in a text field.

Here is what I'm working with:

<tr v-for="review in reviews" v-bind:reviewLoc="review.reviewLocation">
  <td style="vertical-align:middle;">{{review.id}}</td>
  <td><input class="form-control" v-model="review.reviewUser" placeholder="{{review.reviewUser}}"/></td>
  <td><input class="form-control" v-model="review.reviewBody" placeholder="{{review.reviewBody}}"/></td>
  <td>
    <select class="form-control " v-model="reviewSelectedLocationName">
      <option v-for="(location, index) in locations" :value="location.locationName" :selected="location.id == review.reviewLocation" >
        {{location.locationName}}
      </option>
    </select></td>
  <td style="white-space: nowrap; text-align: right;"><button class="btn btn-info" type="button" @click="updateReview(review)"><i class="fa fa-save"></i></button><button class="btn btn-danger ml-1" type="button" @click="deleteReview(review.id)"><i class="fa fa-trash"></i></button></td>
</tr>

Specifically, my issues are with this loop.

 <option v-for="(location, index) in locations" :value="location.locationName" :selected="location.id == review.reviewLocation" >
   {{location.locationName}}
 </option>

As you can see, my goal is to populate to make the option selected by pulling from a list of {{{location.LocationName}}}} and comparing its value to the one at {{review.reviewLocation}}}

I thought basing selected=" on whether or not locationName was equal to reviewLocation would work, but I'm having no luck.

Any help would be appreciated, been stuck on this simple issue all day.

I think the issue is that you have set v-model="reviewSelectedLocationName" on your <select> tag, which dictates what option is selected. You could give each item in reviews a selectedLocation which is initially the same as the reviewLocation , and add v-model="review.selectedLocation" instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM