You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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>

关键修改说明

  1. 父组件修正:将模板中的state.filter改为filter,与脚本中定义的响应式变量对应。
  2. 子组件数据流优化:
    • 新增tableFilter Prop,接收父组件传递的初始过滤对象,遵循Vue单向数据流规则。
    • 使用computed的get/set方法创建localFilter作为输入框的绑定目标,既保证不直接修改props,又能在值变化时统一触发更新事件。
    • 移除每个输入框的@update:model-value重复绑定,简化代码结构。
  3. 默认值完善:为locationList添加默认空数组,避免未传递时出现报错。

内容的提问来源于stack exchange,提问作者Abnormal Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:40:31