In the process of project development, it is inevitable to call the method in the child component in the parent component, using the following
in vue2 project
// 父组件
<Children ref="child"></Children>
<script>
mounted() {
this.$refs.child.XXX() // XX为子组件的一个方法名
}
</script>
in vue3 project
// 父组件
<Children ref="child"></Children>
<script>
import {
onMounted, ref } from 'vue'
setup() {
const child = ref()// child要和子组件的ref值一致
onMounted(() => {
child.value.XX() // XX为子组件的一个方法名
})
return {
child// 此处一定要return,否则获取到的child.value是undefined
}
}
</script>