Vue3获取组件实例的办法

4,290 阅读1分钟

一、vue2中获取dom

首先给dom元素用ref="xxx"命名

然后使用this.$refs.xxx 即可

<template>
  <h1 ref="h1Ref">我是一个孤独可怜又能吃的h1</h1>
</template>

<script>
export default {
    mounted(){
        console.log(this.$refs.h1Ref) // h1
    }
}
</script>

二、vue3中获取dom

方式1:

首先给dom元素用ref=""命名

然后声明在setup中一个响应式变量,这个变量的名字要和ref命名一致

重要:要想获取这个dom必须在onMounted中,因为setup替代了原来的created

<template>
  <div ref="myRef">HelloWorld</div>
</template>

<script setup lang="ts">
    import { ref, onMounted } from 'vue'
    const myRef = ref<null | HTMLElement>(null)
   
    onMounted(() => {
      console.log(myRef.value)
    })
  }
})
</script>

方式2:

使用getCurrentInstance()api

<template>
  <div ref="myRef">HelloWorld</div>
</template>

<script setup lang="ts">
    import { onMounted } from 'vue'
    const { proxy } = getCurrentInstance()
    // proxy.$refs["myRef"]
    onMounted(() => {
      console.log(proxy.$refs["myRef"])
    })
  }
})