vue2中获取

<template>
  <div>
    <div @click="toGetDom">点击获取</div>
    <div ref="divDom">666</div>
  </div>
</template>
 
<script>
export default {
  methods: {
    toGetDom() {
      console.log(this.$refs.divDom);
    },
  },
};
</script>

vue3中获取

<template>
  <div @click="toGetDom">点击获取</div>
  <div ref="divDom">666</div>
</template>
 
<script setup>
import { ref, getCurrentInstance, onMounted } from "vue";
// 声明一个变量来保存获取的dom
let dom = ref(null);
// vue3中使用getCurrentInstance()来获取dom
onMounted(() => {
  // 在生命周期中获取
  dom = getCurrentInstance();
});
let toGetDom = () => {
  // 在点击事件中获取到
  console.log(dom.refs.divDom);
};
</script>

xxnobug
34 声望1 粉丝