Vue3中使用expose无法调用子组件方法的问题求助
Vue组合式API调用子组件暴露方法报错问题
我未使用<script setup>和defineExpose,尝试通过Vue组合式API的expose方法暴露子组件方法供父组件调用,但点击父组件按钮时出现以下两种错误之一:
checklistElm.validate is not a functionchecklistElm.value is null
子组件代码
<script> import { defineComponent } from 'vue'; export default defineComponent({ name: 'Checklist', setup(props, { expose }) { const validateForm = () => { let ok = true; console.log("validate"); return ok; } expose({ validate: validateForm }); } }) </script>
父组件原代码
<template> <div> <Checklist ref="checklistElm" /> <q-btn @click="save">Save</q-btn> </div> </template> <script> import { defineComponent, ref } from 'vue'; export default defineComponent({ name: 'ChecklistPage', components: { Checklist }, setup() { const checklistElm = ref(null); return { save() { let ok = checklistElm.validate(); /* or let ok = checklistElm.value.validate(); */ } } } }) </script>
错误原因及解决方案
错误原因分析
checklistElm.validate is not a function:checklistElm是用ref创建的响应式容器,必须通过.value才能访问内部的组件实例,直接调用checklistElm.validate()是在响应式对象本身上查找方法,必然不存在。checklistElm.value is null:核心问题是父组件的checklistElm这个ref未暴露到模板作用域中——模板里的ref="checklistElm"需要绑定到setup返回的响应式变量上,否则无法正确获取子组件实例;另外也可能是组件未挂载完成就调用方法导致的。
修正后的父组件代码
<template> <div> <Checklist ref="checklistElm" /> <q-btn @click="save">Save</q-btn> </div> </template> <script> import { defineComponent, ref } from 'vue'; export default defineComponent({ name: 'ChecklistPage', components: { Checklist }, setup() { const checklistElm = ref(null); const save = () => { // 先判断实例是否存在,避免未挂载完成时调用报错 if (checklistElm.value) { const ok = checklistElm.value.validate(); // 后续逻辑 } } // 必须把checklistElm暴露到返回对象中,模板才能正确绑定ref return { checklistElm, save } } }) </script>
内容的提问来源于stack exchange,提问作者user414873
相关产品推荐
相关产品推荐

