Vue.js中如何在文本框keyup事件中获取下拉列表选中值?
Hey there! I see you're trying to access the selected value from your dropdown in the input's keyup event using Vue.js, and ran into issues when adding v-model to the select. Let's get this sorted out.
The Fix Explained
The core issue here is that you weren't properly binding the select to your Vue data with v-model (or maybe had a small misstep when trying it). When you use v-model correctly, Vue handles syncing the selected value to your data property automatically, so you can easily access it in your methods.
Here's what you need to do:
- Add
v-model="selected"to your<select>tag. This binds the selected option's value to theselectedproperty in your data. - In your
convertmethod, you can directly referencethis.selectedto get the dropdown's current value, along withthis.currency_from_amountfor the input's value.
Corrected Full Code
JavaScript
new Vue({ el: "#app", data() { return { currency_from_amount: 0, currencyFromOptions: [], selected: '' // This will hold the selected currency code }; }, methods: { convert: function(event) { // Now you can access both values here console.log("Input amount:", this.currency_from_amount); console.log("Selected currency:", this.selected); // Your conversion logic goes here } }, mounted() { axios .get("https://openexchangerates.org/api/currencies.json") .then(response => (this.currencyFromOptions = response.data)) .catch(error => { console.log(error); }) .finally(() => (this.loading = false)); } });
HTML
<script src="https://cdn.jsdelivr.net/npm/vue"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script> <div id="app"> <input class="form-control" type="number" name="currency_from_amount" id="currency_from_amount" v-model="currency_from_amount" @keyup="convert" > <select class="form-control" name="currency_from_code" id="currency_from_code" v-model="selected" <!-- Added v-model binding here --> > <option v-for="(value,key) in currencyFromOptions" :value="key">{{ value }}</option> </select> </div>
Why Your Earlier Attempt Might Have Failed
If adding v-model broke your dropdown before, it's likely not because of v-model itself. Common issues could be:
- Typos in the data property name (e.g., misspelling
selected) - Not initializing the
selectedproperty in your data object - Expecting an initial selected value but not setting
selectedto a valid currency code (like'USD') on mount
With the code above, everything should work as expected: whenever you type in the input, the convert method will fire, and you'll have access to both the input amount and the selected currency.
内容的提问来源于stack exchange,提问作者Steve

