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

Vue3父组件formTelemarketing向子组件nAsignedCalls传值失败求助

问题分析
  1. 数据流逻辑完全错误:你当前的父组件通过$emit触发事件,同时在父组件内的子组件标签上监听该事件,这违背了父子组件传值的基本逻辑——父传子用props,子传父才用$emit。
  2. 数据类型不匹配:父组件定义props: { register: Number },但API返回的是数组格式[{"id":895,...}],类型完全不符;且父组件根本没把获取到的数据通过props传递给子组件。
  3. Composition API使用混乱:代码混合了选项式API(如this.$emit)和Composition API写法,可能导致响应式追踪失效。
解决步骤

1. 修正父组件逻辑(Composition API 标准写法)

父组件无需定义register props,而是自行声明响应式变量存储API数据,再通过props传递给子组件:

<script setup>
import { ref } from 'vue'
import nAsignedCalls from './nAsignedCalls.vue'

// 声明响应式变量存储API返回结果
const registerData = ref([])

// 点击按钮触发的搜索函数
const searchRegisters = async () => {
  // 调用API获取数据,假设getCall返回Promise
  const apiRes = await getCall(toRef(param_search, 'param_search'))
  // 将API返回的data赋值给响应式变量
  registerData.value = apiRes.data
}
</script>

<template>
  <button @click="searchRegisters">搜索数据</button>
  <div id="app5">
    <!-- 父组件通过props绑定将数据传给子组件 -->
    <nAsignedCalls :register="registerData"></nAsignedCalls>
  </div>
</template>

2. 修正子组件的props与渲染逻辑

子组件明确props的类型为数组,通过v-for渲染表格:

<script setup>
import { defineProps } from 'vue'

// 用Composition API的defineProps定义props,指定类型为数组
const props = defineProps({
  register: {
    type: Array,
    default: () => [] // 默认值设为空数组
  }
})
</script>

<template>
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>名称</th>
      </tr>
    </thead>
    <tbody>
      <!-- 判断数组是否为空,为空显示vacio,否则循环渲染数据 -->
      <tr v-if="register.length === 0">
        <td colspan="2">vacio</td>
      </tr>
      <tr v-for="item in register" :key="item.id">
        <td>{{ item.id }}</td>
        <td>{{ item.name }}</td>
      </tr>
    </tbody>
  </table>
</template>

关键错误说明

  • 之前完全搞反了父子传值方向:父组件应持有数据,通过:绑定props传递给子组件,而非父组件触发$emit事件。
  • 必须确保API返回的数据赋值给响应式变量(registerData.value = apiRes.data),Vue才能追踪数据变化并更新视图。
  • 子组件props类型要与传递的数据匹配,API返回数组就设为Array类型,避免类型不匹配导致的静默失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 21:12:27