我尝试在子组件上调用方法,如下所述 https://vuejs.org/api/composition-api-setup.html#exusing-public-properties
请注意,我在这里没有使用<script setup>
and defineExpose
。
子组件
<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 不是一个函数
或者
checklistElm.value 为 null
作为一个错误。不知道为什么...
虽然我在这里使用 Quasar,但这仅指 vue。
您需要使用但您也忘记从设置功能中
.value
返回。checklistElm
如果不返回,它不会暴露给模板,因此ref="checklistElm"
实际上不起作用。这是使用该函数时的常见错误
setup()
。仅供参考,更少的样板代码并且不必记住返回内容是<script setup>
编写 Composition API 组件的推荐方法。