在開發中會遇到這樣的需求:獲取子組件的引用,並調用子組件中定義的方法。如封裝了一個表單組件,在父組件中需要調用這個表單組件的引用,並調用這個表單組件的校驗表單函數或重置表單函數。要實現這個功能,首先要在子組件中暴露父組件需要調用的函數,然後去父組件中獲取子組件的引用,最後通過子組件的引用調用子組件暴 ...
在開發中會遇到這樣的需求:獲取子組件的引用,並調用子組件中定義的方法。如封裝了一個表單組件,在父組件中需要調用這個表單組件的引用,並調用這個表單組件的校驗表單函數或重置表單函數。要實現這個功能,首先要在子組件中暴露父組件需要調用的函數,然後去父組件中獲取子組件的引用,最後通過子組件的引用調用子組件暴露的方法。
1 子組件暴露方法
1.1 SFC(.vue)暴露方法
在使用 .vue 定義的組件中,setup 中提供了 defineExpose() 方法,該方法可以將組件內部的方法暴露給父組件。
創建子組件 demo-component-sfc.vue:
<template>
<el-button type="primary" @click="demoFun('child')">demo component sfc</el-button>
</template>
<script lang="ts" setup name="demo-component-sfc">
const demoFun = (str: string) => {
console.log('demo component sfc', str)
}
// 使用 defineExpose 暴露組件內部的方法
defineExpose({ demoFun })
</script>
1.2 TSX(.tsx)暴露方法
使用 .tsx 方式定義的組件,也是通過參數 context 中的 expose() 方法暴露組件內容的方法。
創建子組件 demo-component-tsx.tsx:
import { defineComponent } from 'vue'
export default defineComponent({
name: 'demo-component-tsx',
setup (props, context) {
const demoFun = (str: string) => {
console.log('demo component tsx', str)
}
// 使用 expose 暴露組件內部的方法
context.expose({ demoFun })
return () => (
<el-button type="primary" onClick={() => demoFun('child')}>demo component tsx</el-button>
)
}
})
2 父組件調用子組件中的方法
2.1 SFC(.vue)調用
在 .vue 文件中獲取組件引用首先定義一個 ref 變數,然後為子組件設置 ref 屬性。ref 屬性值與變數名要保持一致。
import { defineComponent } from 'vue'
export default defineComponent({
name: 'demo-component-tsx',
setup (props, context) {
const demoFun = (str: string) => {
console.log('demo component tsx', str)
}
// 使用 expose 暴露組件內部的方法
context.expose({ demoFun })
return () => (
<el-button type="primary" onClick={() => demoFun('child')}>demo component tsx</el-button>
)
}
})
如上面的代碼所示:第一個子組件的 ref 屬性值為 sfcRef,定義的變數名也是 sfcRef。在父組件中便可以使用 sfcRef 調用子組件的 demoFun 方法了。
2.2 TSX(.tsx)調用
在 .tsx 中獲取組件的引用更簡單,首先定義一個 ref 變數,然後將該變數設置給子組件的 ref 屬性即可。
import { defineComponent, ref } from 'vue'
import DemoComponentSfc from '@/components/ref/demo-component-sfc.vue'
import DemoComponentTsx from '@/components/ref/demo-component-tsx'
export default defineComponent({
name: 'demo-ref-tsx',
setup () {
const sfcRef = ref()
const onBtnClick1 = () => {
if (sfcRef.value) {
sfcRef.value && sfcRef.value.demoFun('parent')
}
}
const tsxRef = ref()
const onBtnClick2 = () => {
if (tsxRef.value) {
tsxRef.value && tsxRef.value.demoFun('parent')
}
}
return () => (
<>
<div>
<DemoComponentSfc ref={sfcRef} />
<el-button onClick={onBtnClick1}>parent button</el-button>
</div>
<div style="margin-top: 10px;">
<DemoComponentTsx ref={tsxRef} />
<el-button onClick={onBtnClick2}>parent button</el-button>
</div>
</>
)
}
})
兩者實現效果一致:
感謝你閱讀本文,如果本文給了你一點點幫助或者啟發,還請三連支持一下,點贊、關註、收藏,作者會持續與大家分享更多乾貨