-
在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>