Vue3 + Ts get dom

In vue2, we usually use this.$refs to obtain DOM elements, but in vue3, setup does not bind this in various ways, so we need to obtain it through other methods.

1. In DOM, the usage of ref is the same as that of vue2.

<div class="score-panel">
       <div>SCORE:<span class="score" ref="scoreSpan">0</span></div>
       <div>LEVEL:<span class="score" ref="levelSpan">1</span></div>
     </div>

2. In the script, you can use getCurrentInstance to get the DOM ( note: it cannot be used directly outside of onMounted() )

<script lang="ts" setup>
import {
    
     ref, onMounted, getCurrentInstance } from "vue";
import {
    
     ScorePanel } from "@/type/sneak";
let refs = null;
onMounted(() => {
    
    
  let {
    
     $refs } = (getCurrentInstance() as any).proxy; 
  // 你可以打印一下(getCurrentInstance() as any)会在 proxy 中发现 $refs
  refs = $refs;
  const scoreSpan = refs.scoreSpan; // 使用refs获取dom
  const levelSpan = refs.levelSpan;
  //下面这是我实例化了一个ScorePanel类,并将获取的DOM传了过去
  const scorePanel = new ScorePanel(scoreSpan, levelSpan) 
  console.log(scorePanel);
});

</script>

In this way, we can use refs to get dom

3. Or you can directly use **document.getElementById("element id")** in onMounted to get the corresponding dom.

Guess you like

Origin blog.csdn.net/weixin_42744724/article/details/128830527