How to obtain the ID Value of a select populated w

2019-08-31 02:09发布

问题:

I have a

<select id="ddlTipoUsuario" class="form-control" >
   <option v-for="tipoUsuario in tipoUsuarios">{{tipoUsuario.Tipo}}</option>
</select>

populated with Vue and axios, but I need to obtain the ID Value to post in another table. In the response.data returns these values:

[ { 
    "TipoUsuarioId": 1, 
    "Tipo": "Administrador" 
  }, 
  { 
    "TipoUsuarioId": 2, 
    "Tipo": "Usuario" 
  } ]

To populate my <select> i use this code:

export default {
    data() {
       return {
           tipoUsuarios:[],
         }
    },
method: {
   getTipoUsuario() {
     axios.get("http://localhost:50995/api/GetTipoUsuario")
     .then(response => {
           this.tipoUsuarios = response.data,
           this.status = response.data
      })
      .catch(e => {
           console.log(e)
      })
   }
}

This is my POST method for now:

 addUsuario() {
            axios.post("http://localhost:50995/api/PostUsuario", {
                "Nombre": this.nombre,
                "ApellidoP": this.apellidoP,
                "ApellidoM": this.apellidoM,
                "Email": this.email,
                "NombreUsuario": this.nombreUsuario,
                "Contrasena": this.password
            })

        },

I need to generate a POST with the value of the ID when i select one option of the <select>.

Thank You.

回答1:

You have to set a v-model on the <select> to a data property to store the selected value, and add the :value to the <option>.

new Vue({
  el: '#example',
  data: {
    types: [{id: 1, name: 'admin'}, {id: 2, name: 'user'}],
    selectedType: 1
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="example">
  <select v-model="selectedType">
      <option 
          v-for="item in types" :value="item.id">
         {{ item.name }}
      </option>
  </select>
  Selected: {{ selectedType }}
</div>

Take a look at the example in Form Input Bindigs: Select from official documentation



回答2:

When you select one of the options, the select will fire a change event, which you can catch and send to a method:

<select id="ddlTipoUsuario" class="form-control" @change="selectChange" >
   <option v-for="tipoUsuario in tipoUsuarios">{{tipoUsuario.Tipo}}</option>
</select>

The method will receive a normal Event object as its argument. You can get the id from it in the usual way:

selectChange(event) {
  this.selectId = event.target.id;
  this.selectedOption = event.target.value; // you probably also want this
}