vue3.0通信方式之 Ref

Ref通信方式

父传子

<template>
  <div>
      <Child ref="child"></Child>
      <button @click="show">Show Child Message</button>
  </div>
</template>
<script setup>
import { getCurrentInstance } from '@vue/runtime-core';
import Child from './Child.vue';
const currentInstance = getCurrentInstance()
function show() {
  currentInstance.refs.child.alertMessage()
}
</script>
  • 通过将getCurrentInstance()进行实例化,再调用refs(currentInstance.refs)下选择child(与绑定子组件的ref值一致),就可以获取到子组件中通过defineExpose({})导出的参数,就可以在父组件使用子组件的一些参数和方法
  • 我们在点击父组件的button按钮时,触发子组件的方法,然后就出现了弹出框alert()

子传父

// Child.vue
<template>
  <div>
      <h1>{{ message }}</h1>
  </div>
</template>
<script setup>
import { ref } from '@vue/reactivity';
let message = ref('我是子元素').value
const alertMessage = function () {
  alert(message)
}
defineExpose({
  message,
  alertMessage
})
</script>

@vue/runtime-core 中的 getCurrentInstance 函数用于获取当前组件实例的引用。在 Vue 2 中我们可以通过 this 关键字来访问当前组件实例,但是在 Vue 3 中使用 setup 函数时,我们并不能通过 this 访问到当前组件实例,而是需要使用 getCurrentInstance 来获取当前组件实例的引用。

使用 getCurrentInstance 可以获取到当前组件实例的各种属性和方法,比如 $props$emit$parent 等。这些属性和方法可以在 setup 函数中被访问和使用。

例如,我们可以使用 getCurrentInstance().$props 来访问当前组件实例的 props 属性,使用 getCurrentInstance().$emit() 来触发当前组件实例的自定义事件。此外,我们还可以使用 getCurrentInstance().proxy 获取当前组件实例的响应式代理对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值