vue3父组件获取子组件对象

aries 发表于 2023-02-22 630 次浏览

Vue2中,可以通过this来获取当前组件实例;

Vue3中,在setup中无法通过this获取组件实例,console.log(this)打印出来的值是undefined

在Vue3中,getCurrentInstance()可以用来获取当前组件实例
代码示例:

<template>
<div>
    <child></child>
</div>
</template>
<script lang="ts" setup>
import { getCurrentInstance,ref,nextTick } from 'vue';
import Child from '@/components/child.vue';
const vm= getCurrentInstance();
const setValue = ()=>{
    nextTick(() => {
        let editorRef = vm['ctx'].$refs.editorRef;
        editorRef.setValue(oaUrl.value);
    });
}
</script>

注意

let { proxy } = getCurrentInstance();
const img = proxy .$refs['img']

或者参考官方文档

<script setup>
import { ref, onMounted } from 'vue'

// 声明一个 ref 来存放该元素的引用
// 必须和模板里的 ref 同名
const input = ref(null)

onMounted(() => {
  input.value.focus()
})
</script>

<template>
  <input ref="input" />
</template>

0条评论

如需评论,请填写表单。
换一个

记住我的信息