父传子
<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
获取当前组件实例的响应式代理对象。