《vue3暴露子组件方法》
解决方案
在Vue3中,若想让父组件调用子组件的方法,可以通过ref或者provide/inject的方式实现。这两种方式都可以有效地建立父子组件间的通信桥梁,使父组件能够获取并执行子组件内部定义的方法。
使用ref的方式
这是比较常用的一种思路。
在子组件中定义好要暴露的方法。例如有一个子组件ChildComponent.vue:
vue
<div>
<!-- 子组件模板内容 -->
</div>
</p>
import { defineExpose } from 'vue'
function childMethod(){
console.log('子组件方法被调用了')
}
defineExpose({
childMethod
})
<p>
然后在父组件中引入子组件并使用ref来获取子组件实例,从而调用其方法。父组件ParentComponent.vue代码如下:
vue
<div>
<button>调用子组件方法</button>
</div>
</p>
import ChildComponent from './ChildComponent.vue'
import { ref } from 'vue'
const childRef = ref(null)
function callChildMethod(){
if(childRef.value){
childRef.value.childMethod()
}
}
export default {
components: {
ChildComponent
}
}
<p>
使用provide / inject的方式
这种方式适用于更复杂的场景,比如多层级的组件嵌套等。
子组件中:
vue
<div>
<!-- 内容 -->
</div>
</p>
import {inject} from 'vue'
// 接收来自祖先组件提供的方法调用能力
const callFromParent = inject('callFromParent')
function childMethod(){
console.log('子组件方法被调用了')
}
// 如果需要主动触发给祖先组件一些反馈也可以在这里处理
if(callFromParent){
callFromParent(childMethod)
}
<p>
父组件中:
vue
<div>
<button>调用子组件方法</button>
</div>
</p>
import ChildComponent from './ChildComponent.vue'
import { provide, ref } from 'vue'
let childMethod = null
function setChildMethod(fn){
childMethod = fn
}
function callChildMethod(){
if(childMethod){
childMethod()
}
}
provide('callFromParent',setChildMethod)
export default {
components: {
ChildComponent
}
}
<p>
通过以上两种方式,就可以很好地实现Vue3中父组件对子组件方法的调用操作了。