实战:子组件获取父组件订单信息
最佳实践建议
- 优先使用 props:适合父子组件直接通信,数据流向清晰
- 复杂场景用 eventBus:跨组件通信推荐使用 mitt 库
- 避免过度使用 $parent:会导致组件耦合度高,难以维护
- provide/inject 适用于跨层级:如主题配置、全局状态等
- 大型项目用 Pinia 或 Vuex:管理全局状态,适合复杂应用
根据你的业务场景选择合适的方式,保持组件间低耦合高内聚,提升代码可维护性。
下面使用第一种方式传递
实战:子组件获取父组件订单信息
以你的发货弹窗组件为例,获取父组件的订单ID:
父组件传递订单ID
<template><view class="order-detail"><button @click="showDeliveryPopup">显示发货弹窗</button><DeliveryPopup :orderId="order.id"@delivery-success="handleDelivery"/></view>
</template><script>
import DeliveryPopup from '@/components/DeliveryPopup.vue';export default {components: { DeliveryPopup },data() {return {order: {id: 20230607,amount: 299,status: '待发货'}}},methods: {showDeliveryPopup() {// 显示弹窗},handleDelivery(res) {// 处理发货成功逻辑uni.showToast({title: '发货成功',icon: 'success'});}}
}
</script>
子组件接收并使用订单ID
<template><view class="delivery-popup"><!-- 其他代码 --><text>订单ID: {{ orderId }}</text><button @click="handleSend">确认发货</button></view>
</template><script setup>
import { defineProps, defineEmits } from 'vue';// 定义 props 接收父组件订单ID
const props = defineProps({orderId: {type: Number,required: true}
});const emits = defineEmits(['delivery-success']);const handleSend = () => {// 使用父组件传递的 orderId 构建发货参数const params = {orderId: props.orderId,expressCompanyId: 1,logisticsNo: 'SF123456789'};// 调用发货接口// ...// 通知父组件发货成功emits('delivery-success', {orderId: props.orderId,status: '已发货',// 其他结果数据});
};
</script>