vue3组合式API获取子组件属性和方法的代码实例
作者:椒盐大肥猫
这篇文章主要为大家详细介绍了vue3组合式API获取子组件属性和方法的代码实例,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
在vue2中,获取子组件实例的方法或者属性时,父组件直接通过ref即可直接获取子组件的属性和方法,如下:
// father.vue <child ref="instanceRef" /> this.$ref['instanceRef'].testVal this.$ref['instanceRef'].testFunc() // child.vue data () { return { testVal: '来自子组件的属性' } }, methods: { testFunc() { return '来自子组件的方法' } }
在vue3 组合式API中,在子组件使用defineExpose指定需要暴露的属性和方法,父组件才可以通过ref获取到子组件的属性和方法,如下:
// father.vue <script setup lang="ts"> import ChildInstance from "@/views/component/father-instance/child-instance.vue"; import { ref } from "vue"; const instanceRef = ref(null); const getChildInstance = () => { const childInstance = instanceRef.value; // 通过ref获取子组件实例 console.log(childInstance.childValue); console.log(childInstance.childFunc()); }; </script> <template> <ChildInstance ref="instanceRef" /> <el-button @click="getChildInstance">获取子组件属性和方法</el-button> </template> <style scoped lang="scss"></style>
// child.vue <script setup lang="ts"> import { ref, defineExpose } from "vue"; const childValue = ref("来自子组件的属性"); const childFunc = () => { return "来自子组件的方法"; }; // 使用defineExpose指定需要暴露的属性和方法 defineExpose({ childValue, childFunc }); </script> <template> <div>来自子组件</div> </template> <style scoped lang="scss"></style>
以上就是vue3组合式API获取子组件属性和方法的代码实例的详细内容,更多关于vue3 API获取子组件的资料请关注脚本之家其它相关文章!