Vue Element如何獲取select選擇框選擇的value和label
1 使用watch監(jiān)聽selectedValue的變化
可以使用Element UI中的v-model指令,將選中的值和對應的標簽存儲在data中的變量中
具體代碼如下:
<template> <el-select v-model="selectedValue" placeholder="請選擇"> <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option> </el-select> <div> <div>選擇的值:{{ selectedValue }}</div> <div>對應的標簽:{{ selectedLabel }}</div> </div> </template> <script> export default { data() { return { options: [ { value: 'option1', label: '選項1' }, { value: 'option2', label: '選項2' }, { value: 'option3', label: '選項3' } ], selectedValue: '', selectedLabel: '' }; }, watch: { selectedValue(newVal) { const option = this.options.find(item => item.value === newVal); this.selectedLabel = option ? option.label : ''; } } }; </script>
結果展示:
在template
中,v-model
指令綁定了selectedValue
變量,表示選中的值。
同時,給<el-option>
添加了v-for
循環(huán)生成所有的選項。
當選中的值改變時,使用watch
監(jiān)聽selectedValue
的變化,通過find
方法從options
中找到選中的值對應的選項,并將標簽存儲在selectedLabel
變量中。
最后,將selectedValue
和selectedLabel
顯示在頁面上。
2 @change事件獲取
2.1 只返回選擇的value
<template> <div> <el-select v-model="selectedValue" @change="getSelectValue"> <el-option v-for="option in options" :key="option.value" :label="option.label" :value="option.value" > </el-option> </el-select> </div> </template> <script> export default { data() { return { options: [ { value: 'option1', label: '選項1' }, { value: 'option2', label: '選項2' }, { value: 'option3', label: '選項3' } ], selectedValue: '', }; }, methods: { getSelectValue(data) { console.log('value', data); }, }, }; </script>
結果展示:
2.2 返回選擇的value和label
下面是一個使用@change
獲取element選擇框的值和名稱的Vue示例代碼:
<template> <div> <el-select v-model="selectedOption" @change="handleOptionChange"> <el-option v-for="option in options" :key="option.value" :label="option.label" :value="option.value" > </el-option> </el-select> <p>Selected Option: {{ selectedOption }}</p> <p>Selected Option Label: {{ selectedOptionLabel }}</p> </div> </template> <script> export default { data() { return { options: [ { value: 'option1', label: '選項1' }, { value: 'option2', label: '選項2' }, { value: 'option3', label: '選項3' } ], selectedOption: '', selectedOptionLabel: '', }; }, methods: { handleOptionChange() { this.selectedOptionLabel = this.options.find( (option) => option.value === this.selectedOption ).label; }, }, }; </script>
結果展示:
在這個示例代碼中,我們首先定義了一個el-select
元素,并使用v-model
指令綁定了一個selectedOption
變量,這個變量將用于存儲用戶選擇的選項的值。
接著,我們在el-select
元素上添加了一個@change
事件監(jiān)聽器,當用戶在選擇框中選擇一個選項時,該事件監(jiān)聽器會被觸發(fā)。
handleOptionChange
方法是@change
事件監(jiān)聽器的處理函數,它通過使用find
方法查找用戶選擇的選項的標簽,并將其存儲在selectedOptionLabel
變量中。
最后,我們在模板中將selectedOption
和selectedOptionLabel
變量的值顯示出來。
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue中計算屬性computed和普通屬性method的區(qū)別小結
Vue.js中Computed和Methods是兩種常用的數據處理方式,本文主要介紹了vue中計算屬性computed和普通屬性method的區(qū)別小結,具有一定的參考價值,感興趣的可以了解一下2024-06-06