简体   繁体   English

Vue,获取 select 选项的值和名称

[英]Vue, get value and name of select option

I'm using html and laravel to build select box options in a foreach loop我正在使用 html 和 laravel 在 foreach 循环中构建 select 框选项

This works and populates with ID as value and name as the option.这可以工作并使用 ID 作为值和名称作为选项进行填充。 What I want, and can't quite figure out here, is how to take my function when I call it and get the id and value as separate vue options for a post axios call I'm going to make.我想要但在这里不太清楚的是,当我调用它时如何使用我的 function 并将 id 和 value 作为单独的 vue 选项用于我将要进行的 axios 调用。

So when I select the option and submit the form to call the function, how can I get the ID as one prop and the name as another?因此,当我选择 select 选项并提交表单以调用 function 时,我怎样才能将 ID 作为一个道具而将名称作为另一个道具?

<select>
@foreach($details as $detail)    
<option value="{{$detail->id}}">{{$detail->name}}</option>
@endforeach
</select>

new Vue({
  data: {
    detailID: [''],
    detailName: ['']
  },
  methods: {
   let data = {

                detailID: this.detailID,
                detailName: this.detailName
            };
  }
})

Here is a code example just using vue.js这是一个仅使用 vue.js 的代码示例

Template模板

<div id="app">
  <select v-model="selectedDetailId">
    <option v-for="detail in details" v-bind:value="detail.id">
      {{ detail.name }}
    </option>
  </select>
</div>

Script脚本

new Vue({
  el: '#app',
  data: {
    selectedDetailId: null,
    details: [
      { id: 1, name: 'A' },
      { id: 2, name: 'B' },
      { id: 3, name: 'C' }
    ]
  },
  methods:{
    post(){
       //your selected Id is this.selectedDetailId
    }
  }
})

You can find more details and examples in the official Vue.js docs.您可以在官方 Vue.js 文档中找到更多详细信息和示例。 https://v2.vuejs.org/v2/guide/forms.html#Value-Bindings https://v2.vuejs.org/v2/guide/forms.html#Value-Bindings

Use v-model to bind the selection to your component data.使用v-model将选择绑定到您的组件数据。 See Form input bindings :请参阅Form input bindings

 new Vue({ data: { detailID: "" }, // now you can access the id with this.detailID in your post request })
 <select v-model="detailID"> @foreach($details as $detail) <option value="{{$detail->id}}">{{$detail->name}}</option> @endforeach </select>

And if you need both id and name , one work around could be:如果您同时需要idname ,一种解决方法可能是:

 new Vue({ data: { detail: "" }, // now you can access the id & name with this.detail.split(',') in your post request })
 <select v-model="detail"> @foreach($details as $detail) <option value="{{$detail->id.','.$detail->name}}">{{$detail->name}}</option> @endforeach </select>

You would need to set a v-model to your select element and bind the entire object to each option element instead of just the id like you are doing in your example.您需要为您的select元素设置一个 v-model 并将整个 object 绑定到每个option元素,而不是像您在示例中所做的那样仅绑定 id。 Here is a codepen with a simple example.这是一个带有简单示例的代码笔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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