【Vue3】父子组件传值、方法调用

Talk is cheap, show me the code.

环境 | Environment

kversion
OSwindows 10
vue3.2.47
javascriptES5+

defineProps 和 defineEmits

definePropsdefineEmits 只能在<script setup>中使用的编译器宏。

它们不需要使用import导入,且会随着<script setup>的处理过程一同被编译掉。

在子组件中的基本使用方式如下:

<script setup>
const props = defineProps({
  msg: String
})

const emit = defineEmits(['load-data'])
</script>

子组件调用父组件的方法 defineEmit

父组件

<template>
	<div>
        <add-modal ref="addModal" @load-data="loadData" />
	</div>
</template>

<script setup>
function loadData() {
    // ...
}
</script>

子组件

<template>
    <div></div>
</template>

<script setup>
// 引入
const emit = defineEmits(['load-data'])

function handleClickSubmit() {
    validate().then(res => {
        addAPI(data).then(res => {
            if (res.success) {
                // 使用
                emit("load-data")
            }
        })
    }).catch(err => {
        console.error('error', err);
    });
}
</script>

参考 | References

优快云 - Vue3-子组件调用父组件的方法、父组件给子组件传值,defineEmits、defineProps

### Vue3父子组件方法调用 #### 父组件向子组件递属性 (Props) 在 Vue3 中,父组件可以通过 `props` 向子组件递数据。这通常用于单向下行通信,即从父到子的数据流动。 ```html <!-- ParentComponent.vue --> <template> <ChildComponent :message="parentMessage" /> </template> <script setup> import { ref } from &#39;vue&#39;; const parentMessage = ref(&#39;Hello Child&#39;); </script> ``` 子组件接收这些属性并将其作为只读变量处理: ```html <!-- ChildComponent.vue --> <template> <p>{{ message }}</p> </script> <script setup> defineProps([&#39;message&#39;]); </script> ``` 这种方式确保了数据流清晰可见,并保持良好的封装性[^2]。 #### 子组件向父组件发送消息 ($emit) 对于自下而上的通讯需求,则可以利用 `$emit()` 方法触发自定义事件通知父级更新状态或执行特定逻辑操作。 ```html <!-- ChildComponent.vue --> <button @click="$emit(&#39;updateParent&#39;, newValue)">Update Parent Value</button> ``` 对应的父组件监听此事件并对之作出响应: ```html <!-- ParentComponent.vue --> <ChildComponent @update-parent="handleValueChange"/> ... methods: { handleValueChange(newValue){ console.log(`New value received:${newValue}`); } } ``` 这种机制允许灵活地建立双向交互模式而不破坏原有架构设计原则[^3]. #### 调用子组件内部函数 有时可能需要直接访问某个嵌套较深的孩子实例中的公共 API 。为此可以在模板里给目标元素加上引用标记(ref),之后便可通过该句柄来操纵它所指向的对象。 ```html <!-- ParentComponent.vue --> <template> <child-component ref="myChild"></child-component> </template> <script setup> import { onMounted, ref } from "vue"; let myChild = ref(null); onMounted(() => { if(myChild.value && typeof myChild.value.someMethod === &#39;function&#39;){ myChild.value.someMethod(); } }); </script> ``` 注意这里使用的是组合式API (`setup`)语法糖形式下的写法,在选项式API中会略有不同[^4]. #### 定义暴露接口(expose) 为了让外部能够安全可靠地获取到某些成员变量或是调用指定的服务端口,可在子组件内声明哪些部分是可以被外界接触得到的。 ```javascript // ChildComponent.vue export default{ ... expose:[&#39;publicApi&#39;], methods:{ publicApi(){ alert("This is a exposed method"); } } }; ``` 这样做的好处在于既保护了私有字段不被随意篡改同时也提供了必要的开放程度满足实际应用场景的需求[^1].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值