在 Vue 组件中,我们经常需要在父组件中访问子组件中定义的变量。在 Vue 2.x 中,我们可以通过
$refs
来访问子组件实例,从而访问子组件中定义的变量或方法。但是在 Vue 3.x 中,由于组合式 API 的引入,$refs
不再推荐使用。那么在 Vue 3.x 中,如何访问子组件中定义的变量呢?
通过 props 传递数据
在 Vue 3.x 中,我们可以通过 props
来传递数据,从而访问子组件中定义的变量。例如,假设子组件定义了一个 message
变量,可以通过以下方式访问:
子组件:
<template>
<div>{
{ message }}</div>
</template>
<script setup>
const message = 'Hello World!'
</script>
父组件:
<template>
<div>
<child-component :message="hello"></child-component>
</div>
</template>
<script setup>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
const hello = ref('Hello World!')
</script>
在子组件中,我们定义了一个 message
变量。在父组件中,我们通过 :message="hello"
将父组件中的 hello
变量传递给子组件,并在子组件中使用 {
{ message }}
来显示 message
变量的值。
通过 ref 引用子组件
在 Vue 3.x 中,我们可以使用 ref
函数来引用子组件实例,进而访问子组件中定义的变量或方法。例如,假设子组件定义了一个 message
变量,可以通过以下方式访问:
子组件:
<template>
<div>{
{ message }}</div>
</template>
<script setup>
const message = 'Hello World!'
</script>
父组件:
<template>
<div>
<child-component ref="child"></child-component>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import ChildComponent from './ChildComponent.vue'
const childRef = ref(null)
onMounted(() => {
console.log(childRef.value.message) // 子组件的 message 变量
})
</script>
在子组件中,我们定义了一个 message
变量。在父组件中,我们使用 ref
函数创建一个响应式引用,并将其命名为 childRef
。在 onMounted
钩子函数中,我们通过 childRef.value
访问子组件的实例,并从中获取 message
变量。
通过 defineExpose 暴露变量或方法
在 Vue 3.x 中,我们还可以使用 defineExpose
函数将子组件中的变量或方法暴露给父组件。例如,假设子组件定义了一个 message
变量,可以通过以下方式访问:
子组件:
<template>
<div>{
{ message }}</div>
</template>
<script setup>
const message = 'Hello World!'
defineExpose({
message
})
</script>
父组件:
<template>
<div>
<child-component ref="child"></child-component>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import ChildComponent from './ChildComponent.vue'
const childRef = ref(null)
onMounted(() => {
console.log(childRef.value.message) // 子组件的 message 变量
})
</script>
在子组件中,我们定义了一个 message
变量,并使用 defineExpose
函数将其暴露给父组件。在父组件中,我们可以通过 childRef.value.message
访问子组件的 message
变量。
总结
在 Vue 3.x 中,我们可以通过 props
、ref
和 defineExpose
来访问子组件中定义的变量或方法。其中,props
适用于父子组件之间的数据传递;ref
适用于访问子组件中的实例,进而访问子组件中的变量或方法;defineExpose
适用于将子组件中的变量或方法暴露给父组件。