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

Nuxt.js中如何用Props、Emit实现三组件间数据传递?

组件间Props+Emit数据传递实现方案

组件关系梳理

Main是父组件,负责维护核心数据;Input是子组件,负责用户输入并同步数据到父组件;CreditCard是子组件,接收父组件传递的数据并展示。以下是分步实现代码:


1. Main组件(父组件)

负责定义响应式数据,绑定Input组件同步输入值,再将数据传递给CreditCard。

<template>
  <div>
    <!-- 用v-model语法糖实现双向数据同步 -->
    <Input type="text" id="cardnumber" labelText="CVV *" v-model="card.cvv" />
    
    <p>当前CVV值:{{ card.cvv }}</p>
    <!-- 将cvv数据通过props传给CreditCard -->
    <CreditCard :cvv="card.cvv" />
  </div>
</template>

<script setup>
import { reactive } from 'vue';
import Input from './Input.vue';
import CreditCard from './CreditCard.vue';

// 定义响应式数据存储卡片信息
const card = reactive({
  cvv: ''
});
</script>

2. Input组件(子组件)

接收父组件传递的初始值,监听输入变化并通过emit通知父组件更新数据。

<template>
  <div>
    <label :for="id">{{ labelText }}</label>
    <input 
      :type="type" 
      :id="id"
      class="border border-smoke text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
      :value="modelValue"
      @input="$emit('update:modelValue', $event.target.value)"
      required
    />
  </div>
</template>

<script setup>
// 定义组件接收的props,v-model默认使用modelValue作为prop名
defineProps({
  type: {
    type: String,
    default: 'text'
  },
  id: {
    type: String,
    required: true
  },
  labelText: {
    type: String,
    required: true
  },
  modelValue: {
    type: String,
    default: ''
  }
});

// 定义需要触发的emit事件
defineEmits(['update:modelValue']);
</script>

如果不想用v-model语法糖,也可以手动绑定prop和监听emit:

<!-- Main组件中调用Input的方式改为 -->
<Input type="text" id="cardnumber" labelText="CVV *" :cvv="card.cvv" @update:cvv="card.cvv = $event" />

<!-- Input组件对应修改为 -->
<template>
  <div>
    <label :for="id">{{ labelText }}</label>
    <input 
      :type="type" 
      :id="id"
      class="border border-smoke text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
      :value="cvv"
      @input="$emit('update:cvv', $event.target.value)"
      required
    />
  </div>
</template>

<script setup>
defineProps({
  type: String,
  id: String,
  labelText: String,
  cvv: String
});

defineEmits(['update:cvv']);
</script>

3. CreditCard组件(子组件)

接收父组件传递的cvv值并展示,只需完善props定义即可:

<template>
  <div>
    <p class="text-graphene font-bold">{{ cvv }}</p>
  </div>
</template>

<script setup>
defineProps({
  cvv: {
    type: String,
    default: ''
  }
});
</script>

核心逻辑说明

  • 父组件Main作为数据的唯一来源,避免多组件维护数据导致的混乱
  • Input组件通过props获取初始值,通过emit将输入变化告知父组件,由父组件更新数据源
  • CreditCard组件通过props接收父组件的数据源,数据变化时自动更新展示
  • v-model是Vue提供的语法糖,本质就是props: modelValue + emit: update:modelValue,使用起来更简洁高效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:24:22