Vue.js中如何获取select选中option的price属性值
获取Vue Select选中Option的Price属性值
嘿,这问题很常见,我给你两种靠谱的解决办法,你可以根据自己的场景选:
方法一:通过DOM元素获取(适合不想改动现有v-model结构的情况)
你已经能拿到event.target了,那只需要找到选中的<option>元素,再读取它的price属性就行。修改你的change_unit方法:
change_unit: function($event) { const selectElement = $event.target; // 找到当前选中的option元素 const selectedOption = selectElement.options[selectElement.selectedIndex]; // 获取price属性值 const selectedPrice = selectedOption.getAttribute('price'); console.log('选中的price:', selectedPrice); }
⚠️ 重要提醒:你当前代码里的price='line.price'是硬编码字符串,不是绑定Vue数据!必须改成:price="line.price"(用v-bind语法),这样才会把line.price的实际值绑定到属性上,否则你拿到的永远是字符串"line.price",而不是你想要的价格数值。修改后的option应该是这样:
<option v-for='(unit) in line.units' :price="line.price" :value='unit.id'>@{{unit['get_unit_id']['name']}}</option> <option selected class='selected' :price="line.price" v-if='line.smallest_unit' :value='line.smallest_unit.id'>@{{line.smallest_unit['name']}}</option>
方法二:Vue化的方式(不操作DOM,推荐)
既然用Vue,我们可以把value改成包含id和price的对象,这样v-model绑定的line.unit就是这个对象,直接读取price就行,不需要碰DOM:
首先修改select的option:
<select v-model='line.unit' name='unit[]' required @change='change_unit'> <option v-for='(unit) in line.units' :value="{ id: unit.id, price: line.price }">@{{unit['get_unit_id']['name']}}</option> <option v-if='line.smallest_unit' :value="{ id: line.smallest_unit.id, price: line.price }">@{{line.smallest_unit['name']}}</option> </select>
然后修改change_unit方法(甚至可以不用传event):
change_unit: function() { // 直接从v-model绑定的line.unit里取price console.log('选中的price:', this.line.unit.price); }
两种方法对比
- 方法一:不需要改变后端接收数据的逻辑(因为value还是unit.id),适合后端只认id的场景,但需要操作DOM元素。
- 方法二:更符合Vue的响应式思想,不用操作DOM,但需要确保后端能处理对象格式的value(或者你提交数据的时候只取
line.unit.id传给后端)。
内容的提问来源于stack exchange,提问作者softya
相关产品推荐
相关产品推荐

