vue2使用Props 传值案例和步骤

本文详细介绍了在Vue2中如何实现父组件向子组件传递数据的过程。具体步骤包括在父组件中声明要传递的值,并在子组件中通过props属性接收这些值。文章还提供了代码示例,展示了如何在子组件中直接使用或通过方法调用获取父组件传递的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue2中父组件给子组件传值可以用props,以下为传值步骤:
1、父组件中声明要传给子组件的值(父组件为minnong.vue,子组件为child.vue)

<child :zsq="sukiTitle"></child>

在这里插入图片描述
2、子组件通过props接收父组件传来的zsq的值

<template>
  <div>
    <h1>我是子组件</h1>
    <p>{{zsq}}-这里可以直接接收父组件的值</p>
    <button @click="showTitle">点击</button>
  </div>
</template>
<script>
export default {
  props: {
    zsq: {
      //此处为要接收的值,zsq为接收过来key
      type: String, //key不能乱写
      default: ""
    }
  },
  methods: {
    showTitle: function() {
      console.log(this.zsq);
      // 点击接收父组件值或者在上面直接接收也行
    }
  }
};
</script>

在这里插入图片描述

<think>根据用户需求,我们需要展示Vue3TypeScript实现父子组件通信的示例。父子组件通信主要包括: 1. 父组件向子组件递数据(Props2. 子组件向父组件递事件(Emits) 我们将创建两个组件:Parent.vue(父组件)Child.vue(子组件)。 示例场景: 父组件递一个字符串消息给子组件,子组件接收并显示。同时,子组件有一个按钮,点击后向父组件发送一个事件(携带数据)。 步骤: 1. 定义子组件的Props使用TypeScript接口) 2. 定义子组件的Emits(使用TypeScript的emit类型定义) 3. 父组件中引入子组件,props并监听子组件事件 代码实现: ### 子组件 Child.vue ```vue <template> <div class="child"> <h3>子组件</h3> <p>收到父组件的消息:{{ message }}</p> <button @click="sendMessageToParent">点击向父组件发送消息</button> </div> </template> <script setup lang="ts"> // 定义Props接口 interface Props { message: string; } // 定义Emits类型 const emit = defineEmits<{ (e: 'childEvent', message: string): void; }>(); // 接收父组件递的props const props = defineProps<Props>(); // 子组件方法:向父组件发送消息 const sendMessageToParent = () => { const childMessage = '你好,父组件!这是来自子组件的消息。'; emit('childEvent', childMessage); }; </script> <style scoped> .child { border: 1px solid #ccc; padding: 20px; margin-top: 20px; } </style> ``` ### 父组件 Parent.vue ```vue <template> <div class="parent"> <h2>父组件</h2> <Child :message="parentMessage" @childEvent="handleChildEvent" /> <p v-if="receivedMessage">收到子组件的消息:{{ receivedMessage }}</p> </div> </template> <script setup lang="ts"> import { ref } from 'vue'; import Child from './Child.vue'; const parentMessage = ref('你好,子组件!这是来自父组件的消息。'); const receivedMessage = ref(''); // 处理子组件发送的事件 const handleChildEvent = (message: string) => { receivedMessage.value = message; }; </script> <style scoped> .parent { padding: 20px; border: 1px solid #333; } </style> ``` ### 说明 1. **Props递**:父组件通过`:message="parentMessage"`将数据递给子组件。子组件通过`defineProps`接收。 2. **事件触发**:子组件通过`defineEmits`定义事件,并通过`emit('childEvent', ...)`触发事件。父组件通过`@childEvent`监听子组件事件,并调用`handleChildEvent`方法处理。 3. **TypeScript类型**:在子组件中,我们使用接口定义了Props的类型,以及emit事件的类型,确保类型安全。 ### 注意事项 - 在Vue3的`<script setup>`语法中,使用`defineProps``defineEmits`无需导入,它们是编译器宏。 - 使用TypeScript可以明确propsemit的类型,减少运行时错误。 ### 运行效果 - 父组件初始化时,将`parentMessage`递给子组件,子组件显示该消息。 - 点击子组件的按钮,子组件触发事件并递消息给父组件,父组件接收到消息后显示在页面上。 这个示例清晰地展示了Vue3TypeScript在父子组件通信中的应用。 §§相关问题§§ 1. Vue3中除了PropsEmits,还有哪些父子组件通信方式? 2. 如何在Vue3中使用TypeScript定义复杂的Props类型(如对象、数组)? 3. Vue3的`<script setup>`语法中,如何定义组件的名称? 4. 在Vue3中,如何实现跨层级组件通信(例如祖孙组件)?</think>### Vue 3 + TypeScript 父子组件通信示例 以下是完整的父子组件通信实现,包含**Props****自定义事件**两种核心方式: #### 1. 子组件 ChildComponent.vue ```vue <template> <div class="child"> <h3>子组件</h3> <p>收到父组件消息:{{ parentMessage }}</p> <button @click="sendToParent">向父组件发送消息</button> </div> </template> <script setup lang="ts"> // 定义Props类型 interface Props { parentMessage: string; count?: number; // 可选属性 } // 接收父组件Props const props = withDefaults(defineProps<Props>(), { count: 0 }); // 定义Emits类型 const emit = defineEmits<{ (e: 'childEvent', message: string): void; (e: 'updateCount', value: number): void; }>(); // 向父组件发送事件 const sendToParent = () => { const response = `子组件于 ${new Date().toLocaleTimeString()} 响应`; emit('childEvent', response); // 触发自定义事件 emit('updateCount', props.count + 1); // 更新父组件数据 }; </script> <style scoped> .child { padding: 15px; border: 2px solid #42b983; margin-top: 10px; } </style> ``` #### 2. 父组件 ParentComponent.vue ```vue <template> <div class="parent"> <h2>父组件</h2> <input v-model="message" placeholder="输入递给子组件的消息" /> <!-- 使用子组件 --> <ChildComponent :parent-message="message" :count="counter" @child-event="handleChildEvent" @update-count="counter = $event" /> <p v-if="childResponse">收到子组件响应:{{ childResponse }}</p> <p>计数器:{{ counter }}</p> </div> </template> <script setup lang="ts"> import { ref } from 'vue'; import ChildComponent from './ChildComponent.vue'; // 响应式数据 const message = ref('初始消息'); const childResponse = ref(''); const counter = ref(0); // 处理子组件事件 const handleChildEvent = (msg: string) => { childResponse.value = msg; console.log('收到子组件消息:', msg); }; </script> <style scoped> .parent { padding: 20px; border: 1px solid #3498db; max-width: 500px; } </style> ``` ### 核心机制说明 1. **Props 向下递**: - 父组件通过 `:parent-message="message"` 递数据 - 子组件通过 `defineProps` 接收并声明类型 - 使用 `withDefaults` 设置默认 2. **事件向上递**: - 子组件通过 `defineEmits` 声明事件类型 - 使用 `emit('eventName', data)` 触发事件 - 父组件通过 `@child-event="handler"` 监听处理 3. **双向数据流**: - 通过 `@update-count="counter = $event"` 实现类似v-model的效果 - 遵循Vue3的"单向数据流"原则,避免直接修改props ### 最佳实践建议 1. **类型安全**: ```ts // 推荐使用接口明确定义 interface Emits { (e: 'submit', payload: UserData): void; } ``` 2. **复杂数据结构**: ```ts // 使用类型别名处理复杂对象 type User = { id: number; name: string; email: string; }; ``` 3. **自定义验证**: ```ts defineProps({ score: { type: Number, validator: (value) => value >= 0 && value <= 100 } }); ``` ### 其他通信方式对比 | 方式 | 适用场景 | Vue3支持度 | |---------------|-------------------------|-----------| | Props/Emits | 父子组件直接通信 | ✅ 首选 | | Provide/Inject| 跨层级组件通信 | ✅ 增强 | | Pinia | 全局状态管理 | ✅ 推荐 | | Event Bus | 任意组件通信(小型项目) | ⚠️ 慎用 | > 提示:对于大型项目,建议使用Pinia状态管理库替代频繁的组件事件递[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值