vue3 组合式API获取子组件的属性和方法

文章比较了Vue2和Vue3中获取子组件实例属性和方法的不同方式,指出在Vue3中,需通过`defineExpose`显式暴露属性以便父组件通过`ref`访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 在vue2中,获取子组件实例的方法或者属性时,父组件直接通过ref即可直接获取子组件的属性和方法,如下:

    // father.vue
    <child ref="instanceRef" />
    this.$ref['instanceRef'].testVal
    this.$ref['instanceRef'].testFunc()
    // child.vue
    data () {
    	return {
    		testVal: '来自子组件的属性'
    	}
    },
    methods: {
    	testFunc() {
    		return '来自子组件的方法'
    	}
    }
    
  2. 在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>
    
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值