如何使用vuejs获取所选选项的文本? [英] How to get the text of the selected option using vuejs?
问题描述
我想获取所选选项输入的文本并将其显示在其他地方.我知道如何使用 jQuery 做到这一点,但我想知道我们如何使用 Vuejs 做到这一点.
这是我们在 jQuery 中的做法.我的意思是 Selected Option 的文本而不是值.
var mytext = $("#customerName option:selected").text();
这是我的 HTML
现在如何在其下显示所选选项.喜欢 Jan、Doe、Khan 吗?
您可以将选定的值与具有两个属性的对象绑定,而不是仅将值定义为 id:值和文本.例如产品:
<select v-model="selected"><option v-for="product in products" v-bind:value="{ id: product.id, text: product.name }">{{ 产品名称 }}</选项></选择>
然后就可以通过value"访问文本了:
值:{{selected.id}}
<h1>文本:{{selected.text}}
var app = new Vue({el: '#app',数据: {选择:'',产品: [{id: 1, name: 'A'},{id:2,名称:'B'},{id:3,名称:'C'}]}})
<select v-model="selected"><option v-for="product in products" v-bind:value="{ id: product.id, text: product.name }">{{ product.name }}</选项></选择><h1>值:{{selected.id}}<h1>文本:{{selected.text}}<script src="https://unpkg.com/vue@2.4.4/dist/vue.js"></script>
I want to get the text of a selected option input and display it somewhere else. I know how to do it using jQuery but I want to know how can we do it using Vuejs.
Here is how we do in jQuery. I mean the text of Selected Option not the value.
var mytext = $("#customerName option:selected").text();
Here is my HTML
<select name="customerName" id="">
<option value="1">Jan</option>
<option value="2">Doe</option>
<option value="3">Khan</option>
</select>
{{customerName}}
Now how can I display the selected option under it. like Jan, Doe, Khan ?
Instead of define the value only as the id, you can bind the selected value with an object with two attributes: value and text. For example with products:
<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>
Then you can access to the text through the "value":
<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>
这篇关于如何使用vuejs获取所选选项的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!