Vue3 父组件调用子组件方法
时间: 2023-11-19 22:51:59 浏览: 166
在 Vue3 中,可以通过 ref
和 appContext
来实现父组件调用子组件方法的功能。具体步骤如下:
在子组件中,使用
ref
定义一个变量,并将需要调用的方法赋值给该变量。例如:<template> <div> <button @click="handleClick">点击</button> </div> </template> <script> import { ref } from 'vue' export default { setup() { const handleClick = () => { console.log('子组件方法被调用') } const childMethod = ref(handleClick) return { childMethod } } } </script>
在父组件中,通过
appContext
获取到子组件实例,并调用子组件的方法。例如:<template> <div> <ChildComponent ref="childRef" /> <button @click="handleClick">调用子组件方法</button> </div> </template> <script> import { onMounted, getCurrentInstance } from 'vue' export default { setup() { const childRef = getCurrentInstance().refs.childRef const handleClick = () => { childRef.childMethod.value() } onMounted(() => { console.log(childRef) // 打印子组件实例 }) return { handleClick } } } </script>
相关推荐















