在组件标签上使用 ref

获取子组件实例

父组件中:

<template>
  <h1>我是 Parent 组件</h1>
  <!--子组件-->
  <Son ref="vmSon"></Son>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import Son, { sonAPI } from './Son.vue'

  //获取子组件实例
  const vmSon = ref<sonAPI | null>(null)
  onMounted(()=>{
    console.log('子组件实例:',vmSon.value)
  })
</script>

子组件:

<template>
  <h3>我是 Son 组件</h3>
</template>

<script setup lang="ts">
  // 暴露子组件接口类型
  export interface sonAPI {}
</script>

<style scoped>

</style>

使用子组件的变量和方法

子组件中:

  import {defineExpose, ref} from 'vue'
  // 暴露子组件接口类型
  export interface sonAPI {
    getName: string,
    setName: any
  }

  let name = ref<string>('seyu')

  function setName(lastName: string): string{
    return name.value += lastName
  }

  // 暴露可被外部访问的属性
  defineExpose({
    getName: name,
    setName,
  })

父组件:

  import { ref, onMounted } from 'vue'
  import Son, { sonAPI } from './Son.vue'

  //获取子组件实例
  const vmSon = ref<sonAPI | null>(null)
  onMounted(()=>{
    console.log('使用子组件的变量:',vmSon.value?.getName)

    setTimeout(()=>{
      //调用子组件的方法
      let newName = vmSon.value?.setName('Buvelly')
      console.log(newName)
    },5000)
  })

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值