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

如何获取子组件数据并传递给父组件?(尝试emit未成功)

子组件点击按钮传递输入框值给父组件的解决方案

你之前用输入框的@change事件触发emit没成功,核心原因是需求是点击按钮时传递值,而非输入框内容变化时传递。下面分Vue3和Vue2给出具体实现代码:

Vue3 实现

子组件(红色区域)

<template>
  <div class="child">
    <input v-model="inputVal" type="text" placeholder="输入答案">
    <button @click="sendAnswer">添加答案</button>
  </div>
</template>

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

// 维护输入框的响应式值
const inputVal = ref('')
// 声明要触发的自定义事件
const emit = defineEmits(['add-answer'])

const sendAnswer = () => {
  // 点击按钮时触发事件,传递输入值
  if (inputVal.value.trim()) {
    emit('add-answer', inputVal.value)
    // 可选:清空输入框
    inputVal.value = ''
  }
}
</script>

父组件(蓝色区域)

<template>
  <div class="parent">
    <!-- 监听子组件的自定义事件 -->
    <ChildComponent @add-answer="receiveAnswer" />
    <!-- 展示接收到的答案 -->
    <div>已添加答案:{{ answerList.join('、') }}</div>
  </div>
</template>

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

const answerList = ref([])

const receiveAnswer = (val) => {
  // 处理接收到的答案,比如存入列表
  answerList.value.push(val)
}
</script>

Vue2 实现

子组件

<template>
  <div class="child">
    <input v-model="inputVal" type="text" placeholder="输入答案">
    <button @click="sendAnswer">添加答案</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputVal: ''
    }
  },
  methods: {
    sendAnswer() {
      if (this.inputVal.trim()) {
        // 触发自定义事件并传值
        this.$emit('add-answer', this.inputVal)
        this.inputVal = ''
      }
    }
  }
}
</script>

父组件

<template>
  <div class="parent">
    <ChildComponent @add-answer="receiveAnswer" />
    <div>已添加答案:{{ answerList.join('、') }}</div>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      answerList: []
    }
  },
  methods: {
    receiveAnswer(val) {
      this.answerList.push(val)
    }
  }
}
</script>

常见错误排查

  1. 事件名不匹配:子组件emit的事件名和父组件监听的名称要一致(Vue中建议用短横线分隔的命名方式)
  2. 未维护输入框的响应式值:确保输入框用v-model绑定了响应式变量,才能正确获取输入内容
  3. 触发时机错误:不要在输入框的@change或@input事件中触发,而是绑定到按钮的@click事件上,符合需求的触发逻辑

内容的提问来源于stack exchange,提问作者Jassem Ben Rayana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:20:52