Vue3父子組件互調(diào)方法的實現(xiàn)
下面演示均為使用 setup 語法糖的情況!
一、父組件調(diào)用子組件方法
下面演示為使用 setup 語法糖的情況,值得注意的是子組件需要使用 defineExpose 對外暴露方法,父組件才可以調(diào)用!
1、子組件
<template> </template> <script setup lang="ts"> // 第一步:定義子組件里面的方法 const doSth = (str: string) => { console.log("子組件的 doSth 方法執(zhí)行了!" + str); } // 第二步:暴露方法 defineExpose({ doSth }) </script> <style scoped> </style>
2、父組件
<template> <button @click="getChild">觸發(fā)子組件方法</button> <!-- 第一步:定義 ref --> <HelloWorld ref="childRef" /> </template> <script setup lang="ts"> // 一、導入 import { ref } from 'vue'; import HelloWorld from './components/HelloWorld.vue'; // 二、數(shù)據(jù) // 第二步:定義與 ref 同名變量 const childRef = ref<any>(); // 三、函數(shù) const getChild = () => { // 第三步: 調(diào)用子組件的方法或者變量,通過value childRef.value.doSth("隨便傳值!"); } </script> <style> </style>
3、測試結果
4、關于 defineExpose 的官方文檔
網(wǎng)址:https://v3.cn.vuejs.org/api/sfc-script-setup.html#defineexpose
defineExpose
使用 <script setup>
的組件是默認關閉的,也即通過模板 ref 或者 $parent
鏈獲取到的組件的公開實例,不會暴露任何在 <script setup>
中聲明的綁定。
為了在 <script setup>
組件中明確要暴露出去的屬性,使用 defineExpose
編譯器宏:
<script setup> import { ref } from 'vue' const a = 1 const b = ref(2) defineExpose({ a, b }) </script>
當父組件通過模板 ref 的方式獲取到當前組件的實例,獲取到的實例會像這樣 { a: number, b: number }
(ref 會和在普通實例中一樣被自動解包)。
二、子組件調(diào)用父組件方法
1、子組件
<template> </template> <script setup lang="ts"> import { onMounted } from "@vue/runtime-core"; const emit = defineEmits([ "doSth" ]); const doSth = () => { emit('doSth'); } onMounted(() => { doSth(); }); </script> <style scoped> </style>
2、父組件
<template> <!-- 第一步:使用 @do-sth 或 @doSth 接受方法 --> <HelloWorld @doSth="sayHello" /> </template> <script setup lang="ts"> // 一、導入 import HelloWorld from './components/HelloWorld.vue'; // 二、函數(shù) // 第二步: 自定義方法 const sayHello = () => { console.log("hello world!"); } </script> <style> </style>
3、測試結果
4、關于 defineEmits 的官方文檔
網(wǎng)址:https://v3.cn.vuejs.org/api/sfc-script-setup.html#defineprops-和-defineemits
defineProps
和 defineEmits
在 <script setup>
中必須使用 defineProps
和 defineEmits
API 來聲明 props
和 emits
,它們具備完整的類型推斷并且在 <script setup>
中是直接可用的:
<script setup> const props = defineProps({ foo: String }) const emit = defineEmits(['change', 'delete']) // setup code </script>
- defineProps 和 defineEmits 都是只在 <script setup> 中才能使用的編譯器宏。他們不需要導入且會隨著 <script setup> 處理過程一同被編譯掉。
- defineProps 接收與 props 選項相同的值,defineEmits 也接收 emits 選項相同的值。
- defineProps 和 defineEmits 在選項傳入后,會提供恰當?shù)念愋屯茢唷?/li>
- 傳入到 defineProps 和 defineEmits 的選項會從 setup 中提升到模塊的范圍。因此,傳入的選項不能引用在 setup 范圍中聲明的局部變量。這樣做會引起編譯錯誤。但是,它可以引用導入的綁定,因為它們也在模塊范圍內(nèi)。
如果使用了 Typescript,使用純類型聲明來聲明 prop 和 emits 也是可以的。
到此這篇關于Vue3父子組件互調(diào)方法的實現(xiàn)的文章就介紹到這了,更多相關Vue3父子組件互調(diào)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue3中defineProps傳值使用ref響應式失效詳解
這篇文章主要給大家介紹了關于vue3中defineProps傳值使用ref響應式失效的相關資料,文章通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2022-03-03