如何在Vue子组件select变更时向父组件传递value与name双属性
Select变更时同步传递value与name属性的实现方案
核心思路:子组件本身已持有完整的
segmentLocations数据源,在select触发变更时,通过当前选中的value值匹配对应条目,即可同时获取到需要传递的value与name两个属性。
子组件修改后完整代码
<template> <div class="container"> <div> <select v-model="selectedSegmentValue" @change="onSegmentChange"> <option selected value="">Choose your location...</option> <option v-for="segmentLocation in segmentLocations" :value="segmentLocation.value" :key="segmentLocation.value"> {{ segmentLocation.name }} </option> </select> </div> </div> </template> <script> export default { data() { return { // 补充原代码遗漏的v-model绑定变量 selectedSegmentValue: "", segmentLocations: [ { value: "Residential", name: 'Residential building' }, { value: "Workplace", name: 'Workplace' }, { value: "Hospitality", name: 'Hospitality or Retail' }, { value: "Real Estate", name: 'Real Estate' }, { value: "Commercial Parking", name: 'Commercial Parking' }, { value: "Fleets", name: 'Fleets' }, { value: "Cities & Governments", name: 'Cities & Governments' }, { value: "Corridor", name: 'Highway, Corridor or Petrol Station' } ], } }, methods: { onSegmentChange(e) { const selectedValue = e.target.value // 匹配当前选中项对应的完整数据 const selectedSegment = this.segmentLocations.find(item => item.value === selectedValue) // 批量传递两个属性给父组件,空选项时name返回空字符串 this.$emit('selectLocation', { value: selectedValue, name: selectedSegment ? selectedSegment.name : '' }) } } }; </script>
父组件修改后完整代码
<template> <Segments @selectLocation="handleSegmentChange" :selectedValue="quote.selectedSegmentValue"> </Segments> </template> <script> export default { data() { return { quote: { selectedSegmentValue: "", selectedSegmentName: "" }, }; }, methods: { handleSegmentChange(payload) { this.quote.selectedSegmentValue = payload.value this.quote.selectedSegmentName = payload.name } } }; </script>
补充说明
- 原生select的value仅支持字符串类型,无法直接绑定整个对象作为option值,上述数组匹配是最兼容的实现方案
- 若偏好多参数传递的写法,可将子组件的emit逻辑调整为
this.$emit('selectLocation', selectedValue, selectedSegment?.name || ''),父组件的接收方法改为handleSegmentChange(val, name) { ... }即可
内容的提问来源于stack exchange,提问作者madameFerry
相关产品推荐
相关产品推荐

