Vue子组件如何将所有输入值以对象形式传递给父组件?
实现子组件输入值整合为对象传递给父组件的方案
完全可行,只需调整组件的数据流逻辑,遵循Vue单向数据流原则,即可实现将子组件所有输入值整合为指定格式对象传递给父组件。以下是优化后的代码实现:
修正后的父组件
<template> <table-filter v-model:tableFilter="filter" /> </template> <script setup> import { ref } from 'vue'; // 初始化过滤对象,将接收子组件传递的整合值 const filter = ref({}); </script>
优化后的子组件
<template> <div class="col"> <q-input outlined dense v-model="localFilter.name" placeholder="Name" class="q-mr-md-sm" > <template v-slot:prepend> <q-icon name="search" /> </template> </q-input> </div> <div class="col"> <q-select outlined dense v-model="localFilter.country" :options="countryList" label="Country" map-options emit-value hide-bottom-space clearable /> </div> <div class="col"> <q-select outlined dense v-model="localFilter.location" label="Location" :options="locationList" emit-value map-options clearable hide-bottom-space /> </div> </template> <script setup> import { PropType, computed } from 'vue'; const props = defineProps({ // 接收父组件传递的过滤对象 tableFilter: { type: Object, default: () => ({}) }, countryList: { type: Object, default: () => ({}) }, locationList: { type: Array as PropType<Array<string>>, default: () => [] }, }); const emit = defineEmits(['update:tableFilter', 'reset']); // 通过computed实现双向绑定的中间层,避免直接修改props const localFilter = computed({ get() { // 返回父组件传递对象的拷贝,保证初始值一致 return { ...props.tableFilter }; }, set(newVal) { // 值变化时统一触发事件,将最新整合对象传给父组件 emit('update:tableFilter', newVal); } }); </script>
关键修改说明
- 父组件修正:将模板中的
state.filter改为filter,与脚本中定义的响应式变量对应。 - 子组件数据流优化:
- 新增
tableFilterProp,接收父组件传递的初始过滤对象,遵循Vue单向数据流规则。 - 使用
computed的get/set方法创建localFilter作为输入框的绑定目标,既保证不直接修改props,又能在值变化时统一触发更新事件。 - 移除每个输入框的
@update:model-value重复绑定,简化代码结构。
- 新增
- 默认值完善:为
locationList添加默认空数组,避免未传递时出现报错。
内容的提问来源于stack exchange,提问作者Abnormal Dev
相关产品推荐
相关产品推荐

