如何使用 vuejs 获取所选选项的文本

How to get the text of the selected option using vuejs?

本文关键字:选项 文本 何使用 vuejs 获取      更新时间:2023-09-26

我想获取所选选项输入的文本并将其显示在其他地方。我知道如何使用jQuery来做到这一点,但我想知道如何使用Vuejs来做到这一点。

以下是我们在jQuery中的做法。我的意思是所选选项的文本而不是值。

var mytext = $("#customerName option:selected").text();

这是我的网页

    <select name="customerName" id="">
         <option value="1">Jan</option>
         <option value="2">Doe</option>
         <option value="3">Khan</option>
   </select>
 {{customerName}}

现在,我如何在其下显示所选选项。 像扬,多伊,汗?

您可以将所选值与具有两个属性的对象绑定,而不是仅将值定义为 id:值和文本。例如产品:

<div id="app">
   <select v-model="selected">
       <option v-for="product in products" v-bind:value="{ id: product.id, text: product.name }">
         {{ product.name }}
       </option>
   </select>
</div>

然后,您可以通过"值"访问文本:

   <h1>Value:
     {{selected.id}}
   </h1>
   <h1>Text:
     {{selected.text}}
   </h1>

工作示例

var app = new Vue({
  el: '#app',
  data: {
  	selected: '',
    products: [
      {id: 1, name: 'A'},
      {id: 2, name: 'B'},
      {id: 3, name: 'C'}
    ]
  }
})
<div id="app">
   <select v-model="selected">
       <option v-for="product in products" v-bind:value="{ id: product.id, text: product.name }">{{ product.name }}
       </option>
   </select>
   <h1>Value:
   {{selected.id}}
   </h1>
   <h1>Text:
   {{selected.text}}
   </h1>
</div>
<script src="https://unpkg.com/vue@2.4.4/dist/vue.js"></script>

我遇到了这个问题,我需要从选定的选项中获取数据属性,这是我的处理方式:

<select @change="handleChange">
    <option value="1" data-foo="bar123">Bar</option>
    <option value="2" data-foo="baz456">Baz</option>
    <option value="3" data-foo="fiz789">Fiz</option>
</select>

在 Vue 方法中:

methods: {
    handleChange(e) {
        if(e.target.options.selectedIndex > -1) {
            console.log(e.target.options[e.target.options.selectedIndex].dataset.foo)
        }
    }
}

但是您可以更改它以获得innerText或其他任何东西。如果你使用的是jQuery,你可以$(e).find(':selected').data('foo')$(e).find(':selected').text()更短一点。

如果要将模型绑定到选择元素,则只有在未设置值时(如提交表单时)时,它只会返回值(如果已设置)或选项的内容。

**编辑**

我想说的是,@MrMojoRisin给出的答案是一种更优雅的解决这个问题的方法。

下面的代码用于从所选选项中获取文本。我添加了一个 v-on:change ,它调用一个函数 onChange() 到选择元素。

methods:{
    onChange: function(e){
        var id = e.target.value;
        var name = e.target.options[e.target.options.selectedIndex].text;
        console.log('id ',id );
        console.log('name ',name );
    },

 <select name="customerName" id="" v-on:change="onChangeSite($event)">
         <option value="1">Jan</option>
         <option value="2">Doe</option>
         <option value="3">Khan</option>
   </select>

假设您的模型上有一个customers列表和选定的customer,如下所示的示例应该可以完美运行:

<select v-model="theCustomer">
    <option :value="customer" v-for="customer in customers">{{customer.name}}</option>
</select>
<h1>{{theCustomer.title}} {{theCustomer.name}}</h1>

我想你的值应该在JS中。然后你可以很容易地操纵它。只需添加:

data: {
  selected: 0,
  options: ['Jan', 'Doe', 'Khan']
}

您的标记将更干净:

<select v-model="selected">
  <option v-for="option in options" value="{{$index}}">{{option}}</option>
</select>
<br>
<span>Selected: {{options[selected]}}</span>

这是更新 JSFiddle

正如th1rdey3所指出的,你可能想要使用复杂的数据,而值不能简单地成为数组的索引。您仍然可以使用 和对象键代替索引。这是实现。

您可以使用 Cohars 样式,也可以使用方法。数据保存在options变量中。showText 方法找出所选值文本并将其返回。一个好处是您可以将文本保存到另一个变量,例如 selectedText

.HTML:

<div id='app'>
  <select v-model="selected">
    <option v-for="option in options" v-bind:value="option.value">
      {{ option.text }}
    </option>
  </select>
  <br>
  <span>Selected: {{ showText(selected) }}</span>
</div>

JAVASCRIPT:

var vm = new Vue({
  el: '#app',
  data: {
    selected: 'A',
    selectedText: '',
    options: [{
      text: 'One',
      value: 'A'
    }, {
      text: 'Two',
      value: 'B'
    }, {
      text: 'Three',
      value: 'C'
    }]
  },
  methods: {
    showText: function(val) {      
      for (var i = 0; i < this.options.length; i++) {
        if (this.options[i].value === val){
          this.selectedText = this.options[i].text;
          return this.options[i].text;
        }
      }
      return '';
    }
  }
});

JSFiddle 显示演示

我试图使用MojoRisin先生的以下建议

v-bind:value="{ id: product.id, text: product.name }"

然而,对我来说,这导致对象的 toString() 表示被分配给值,即 [对象对象]

相反,我在代码中所做的是在绑定到值的类似对象上调用 JSON.stringify

v-bind:value="JSON.stringify({id: lookup[lookupIdFields[detailsSection]], name: lookup.Name})"

然后,我当然可以使用JSON.parse将其转换回对象,并从结果中获取必要的id和名称值

在模板之外,我访问选项的名称,如下所示:

let option_name = this.options[event.target.options.selectedIndex].name

为此,请采用以下方法来设置模板:

在数组中定义您的选项,例如 [{"name":"Bar","value":1},{"name":"Baz","value":2}]......等

将您的选项放在组件的data功能 <script>export default {function data(){return { options }}}</script>

使用 v:for 加载模板中的options<option v-for="option in options" v-bind:value="option.value">{{option.name}}</option>

select元素使用@change="getOptionName"

<select @change="getOptionName">

在您的methods中获取名称:

getOptionName(event){ let option_name = this.options[event.target.options.selectedIndex].name }

请注意,在这种情况下,event.target.options 中的object options与名为 options 的数据没有任何关系...希望这将避免混淆

所以一种更高级的方法,但我相信当它全部正确设置时,获取名称并不可怕,尽管它可能更容易。

الفترة

اختر الفترة {{ period.name }}

<label for="period_id" class="block font-medium text-sm text-gray-700">الفترة</label>
<select v-model="form.period_id" id="period_id" class="border-gray-300">
    <option disabled value="">اختر الفترة</option>
    <option v-for="period in periods" :value="period.id" :selected="building.period_id === period.id ? 'selected' : null">
    {{ period.name }}
    </option>
</select>

你可以在 Vue 文档中找到它: http://vuejs.org/guide/forms.html#Select

使用 V 模型:

<select v-model="selected">
  <option selected>A</option>
  <option>B</option>
  <option>C</option>
</select>
<br>
<span>Selected: {{ selected }}</span>

在您的情况下,我想您应该这样做:

<select name="customerName" id="" v-model="selected">
     <option>Jan</option>
     <option>Doe</option>
     <option>Khan</option>
</select>
{{selected}}

这是一个工作小提琴: https://jsfiddle.net/bqyfzbq2/

我认为这里的一些答案有点太复杂了,所以我想提供一个更简单的解决方案。我只打算在示例中使用事件处理程序,而省略模型绑定等内容。

<select @change="yourCustomMethod">
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

然后在你的 Vue 实例中:

...
methods: {
    yourCustomMethod: function(event) {
        var key = event.target.value, // example: 1
            value = event.target.textContent; // example: One
    }
}
...