vue3父組件調(diào)用子組件方法的思路及實例代碼
更新時間:2025年06月28日 10:16:30 作者:愉快的小跳蛙
在Vue.js框架中父子組件之間的通信是常見的需求,其中父組件調(diào)用子組件的方法是實現(xiàn)特定功能的重要方式,這篇文章主要介紹了vue3父組件調(diào)用子組件方法的相關資料,需要的朋友可以參考下
需求:在vue3中需要在父組件調(diào)用子組件的方法
思路:通過ref和defineExpose直接暴露給父組件
1.子組件暴露表單驗證方法
<template>
<a-form ref="formRef" :model="formState" :rules="rules">
<a-form-item label="用戶名" name="username">
<a-input v-model:value="formState.username" />
</a-form-item>
</a-form>
</template>
<script setup>
import { ref } from 'vue';
const formRef = ref(); // 表單引用
const formState = ref({ username: '' }); // 表單數(shù)據(jù)
const rules = { // 驗證規(guī)則
username: [{ required: true, message: '請輸入用戶名' }]
};
// 暴露給父組件的驗證方法
const validate = () => formRef.value.validate();
defineExpose({ validate }); // 暴露方法
</script>2.父組件觸發(fā)子組件表單驗證
<template>
<ChildForm ref="childFormRef" />
<a-button @click="handleSubmit">提交</a-button>
</template>
<script setup>
import { ref } from 'vue';
import ChildForm from './ChildForm.vue';
const childFormRef = ref(); // 子組件引用
const handleSubmit = async () => {
try {
const values = await childFormRef.value.validate();
console.log('驗證通過,數(shù)據(jù):', values);
// 提交數(shù)據(jù)邏輯...
} catch (error) {
console.log('驗證失敗', error);
}
};
</script>總結
到此這篇關于vue3父組件調(diào)用子組件方法的文章就介紹到這了,更多相關vue3父組件調(diào)用子組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue-router使用next()跳轉到指定路徑時會無限循環(huán)問題
這篇文章主要介紹了vue-router使用next()跳轉到指定路徑時會無限循環(huán)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

