父组件调用子组件的方法,或者访问子组件的变量,在实际运用中很常见,vue2 与 vue3 写法差异如下:
1、vue2用法
在使用 vue2 或仅<script>标签中只需要子组件上写一个ref='xxx'变量,父组件通过this.$refs['xxx']就可以直接访问子组件的方法或变量,如:
子组件有一个方法clear(),vue2或非setup用法时,父组件是这么调用的:
<template>
<div>
<子组件 ref="childRef" />
<button @click="childHandle" />
</div>
</template>
<script>
data(){
return {}
},
methods:{
childHandle(){
this.$refs['childRef'].clear() // this.$refs['xxx']
}
}
</script>
这里子组件里只要data里声明了的变量和methods里声明的方法,父组件就可以直接访问到。
2、vue3用法
子组件是在 vue3 或 <script setup>时,父组件直接调用就会提示clear()法未定义。
官网有这么一句话:使用 <script setup> 的组件是默认关闭的,也即通过模板 ref 或者 $parent 链获取到的组件的公开实例,不会暴露任何在 <script setup> 中声明的绑定。
因此,父组件是不能直接访问子组件的方法,需要子组件手动的抛出才行,使用defineExpose()方法,如下:
子组件中需要如此修改:
<script setup>
import { defineExpose, ref } from 'vue';
const data = ref('');
function clear(){
data.value = ''
}
defineExpose({ clear }) // 使用 defineExpose()方法 暴露出去
</script setup>
父组件调用:
childRef.value.clear()