【问题标题】:How to obtain the ID Value of a select populated with axios and Vue如何获取用 axios 和 Vue 填充的 select 的 ID 值
【发布时间】:2018-08-29 23:25:35
【问题描述】:

我有一个

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

填充了 Vue 和 axios,但我需要获取 ID 值才能发布到另一个表中。 在 response.data 中返回这些值:

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

要填充我的&lt;select&gt;,我使用以下代码:

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)
      })
   }
}

这是我现在的 POST 方法:

 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
            })

        },

当我选择&lt;select&gt; 的一个选项时,我需要生成一个带有ID 值的POST。

谢谢。

【问题讨论】:

  • ID应该去​​哪里?我的意思是,你说你需要它,但不要说你会在哪里使用它。
  • 我需要 POST 方法中的 ID,以将其保存在数据库中
  • 具体在哪里?展示如果你有它,你会怎么做。
  • 对数据库来说,就是表之间的关系。我只是在练习

标签: post drop-down-menu vue.js axios


【解决方案1】:

您必须将&lt;select&gt; 上的v-model 设置为数据属性以存储所选值,并将:value 添加到&lt;option&gt;

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>

看看官方文档Form Input Bindigs: Select中的例子

【讨论】:

    【解决方案2】:

    当您选择其中一个选项时,select 将触发 change 事件,您可以捕获该事件并将其发送到方法:

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

    该方法将接收一个普通的 Event 对象作为其参数。您可以通过通常的方式从中获取id

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 2021-04-07
      • 2018-02-15
      • 2020-10-21
      • 2019-07-03
      相关资源
      最近更新 更多