Vue3 获取DOM元素总结

文章目录

Vue3 获取DOM元素总结

获取单个DOM

vue 复制代码
<script setup>
import {onMounted, ref} from "vue";

const boxRef = ref();

onMounted(() => {
  console.log(boxRef.value);
  boxRef.value.style.backgroundColor = "red"; // 设置背景色
  const myWidth = boxRef.value.clientWidth; // 获取属性
  console.log(myWidth);
});
</script>

<template>
  <div ref="boxRef"></div>
</template>

<style scoped>
div {
  width: 100px;
  height: 100px;
  margin: 10px;
}
</style>

获取多个DOM

需要给 ref 绑定函数,用于收集所有元素。

vue 复制代码
<script setup>
import {onMounted, ref} from "vue";

const itemRefs = ref([]);
const list = ref([{id: 1, name: "A"}, {id: 2, name: "B"}, {id: 3, name: "C"}]);
const setItemRef = (el) => {
  if (el)
    itemRefs.value.push(el);
};

onMounted(() => {
  for (const el of itemRefs.value) {
    console.log(el.innerText);
  }
});
</script>

<template>
  <ul>
    <li v-for="item in list" :key="item.id" :ref="setItemRef">
      {{ item.name }}
    </li>
  </ul>
</template>

<style scoped>
div {
  width: 100px;
  height: 100px;
  margin: 10px;
}
</style>

获取子组件的DOM

方式一:defineExpose

子组件需要调用 defineExpose 暴露DOM元素。

子组件:

vue 复制代码
<script setup>
import {ref} from "vue";

const boxRef = ref();

defineExpose({boxRef});
</script>

<template>
  <div ref="boxRef">
    hello world
  </div>
</template>

父组件:

vue 复制代码
<script setup>
import Child from "@/components/Child.vue";
import {onMounted, ref} from "vue";

const childRef = ref();

onMounted(() => {
  const el = childRef.value.boxRef;
  console.log(el.innerText);
});
</script>

<template>
  <Child ref="childRef"/>
</template>

方式二:$el

可以通过 $el 获取组件的根DOM

vue 复制代码
<script setup>
import Child from "@/components/Child.vue";
import {onMounted, ref} from "vue";

const childRef = ref();

onMounted(() => {
  const el = childRef.value.$el;
  console.log(el.innerText);
});
</script>

<template>
  <Child ref="childRef"/>
</template>