[vue3]组件操作Dom元素,多个同名ref时的解决方法,返回了proxy对象时的使用

/ 7,962评论 / 39683阅读 / 5点赞

1. 原生js中我们会使用document.getElementsByClassName(),document.getElementById()等获取dom元素,但在vue中,更推荐使用ref获取。

2. 不同文件的ref相互独立,即使同名也不会互相影响而导致获取错误。一个组件被多次引用后同时存在多个实例时,每个实例的ref也是互相独立的。这一点显然比getElementById()要好很多。

3. 标签的ref属性值在每一个vue文件中需要是唯一的,否则可能在获取时发生与预期不同的效果。显然使用v-for时如果单项带有ref就需要我们解决这个问题。

使用ref绑定Dom元素

<template>
    <span id="myspanid" ref="mySpanRef">hello coolight</span>
</template>

获取

获取的方式很多,这里介绍其中的几种,以及提及一些document的方法和注意事项

祖传getElementById()

<script setup>
import { onMounted } from "vue";

let span_id = document.getElementById("myspanid");
console.log("setup: span_id = ", span_id);

onMounted(() => {
    console.log("onMounted: span_id = ", span_id);
    span_id = document.getElementById("myspanid");
    console.log("onMounted: span_id = ", span_id);
})
</script>

<template>
    <span id="myspanid" ref="mySpanRef">hello coolight</span>
</template>

ref(null)

<script setup>
import { ref,onMounted, getCurrentInstance } from "vue";

let mySpanRef = ref(null);
console.log("setup: mySpanRef = ", mySpanRef);
console.log("setup: mySpanRef.value = ", mySpanRef.value);

onMounted(() => {
    console.log("读取setup获取的mySpanRef:");
    console.log("onMounted: mySpanRef = ", mySpanRef);
    console.log("onMounted: mySpanRef.value = ", mySpanRef.value);
    mySpanRef = ref(null);
    console.log("读取onMounted获取的mySpanRef:");
    console.log("onMounted: mySpanRef = ", mySpanRef);
    console.log("onMounted: mySpanRef.value = ", mySpanRef.value);
})
</script>

<template>
    <span ref="mySpanRef">hello coolight</span>
</template>
<script setup>
import { ref, onMounted } from "vue";

const mySpanRef = ref(null);

onMounted(() => {
    console.log(mySpanRef);
    console.log(mySpanRef.clientWidth);
    console.log(mySpanRef.value.clientWidth);
})
</script>

<template>
    <span ref="mySpanRef">hello coolight</span>
</template>

$refs.refName

<script setup>
import { onMounted, getCurrentInstance } from "vue";

let mySpan;

onMounted(() => {
    let { $refs } = (getCurrentInstance()).proxy;
    mySpan = $refs.mySpanRef;
    console.log("onMounted: mySpan = ", mySpan);
})
</script>

<template>
    <span ref="mySpanRef">hello coolight</span>
</template>

$refs[refName]

<script setup>
import { onMounted, getCurrentInstance } from "vue";

let mySpan;

onMounted(() => {
    let { $refs } = (getCurrentInstance()).proxy;
    let name = "mySpanRef";
    mySpan = $refs[name]; 
    //mySpan = $refs['mySpanRef'];      //这个也是可以的
    console.log("onMounted: mySpan = ", mySpan);
})
</script>

<template>
    <span ref="mySpanRef">hello coolight</span>
</template>

多个同名ref的解决方法

上面我们都是把ref当成id一样使用,但在v-for后产生的列表项可能遇到ref重复,下面我们聊聊如何解决这个问题

<script setup>
import { ref, onMounted, getCurrentInstance } from "vue";

let mySpanRef = ref(null);

onMounted(() => {
    console.log("ref(null) = ", mySpanRef.value);
    let { $refs } = (getCurrentInstance()).proxy;
    mySpanRef = $refs.mySpanRef;
    console.log("$refs.mySpanRef = ", mySpanRef);
    mySpanRef = $refs['mySpanRef'];
    console.log("$refs['mySpanRef'] = ", mySpanRef);
})
</script>

<template>
    <div>
        <span ref="mySpanRef">hello coolight</span>
        <span ref="mySpanRef">hello 洛天依</span>
    </div>
</template>
<script setup>
import { onMounted, getCurrentInstance } from "vue";

let arr = ['coolight', '洛天依', 'enter', 'shift', 'ctrl', 'Alt', 'ESC'];

onMounted(() => {
    let { $refs } = (getCurrentInstance()).proxy;
    console.log($refs['myspan0']);
    console.log("for:");
    for(let i = arr.length; i-- > 0;) {
        console.log($refs['myspan'+ i][0]);
    }
})
</script>

<template>
    <div style="display:flex;flex-direction: column;">
        <span v-for="(item, index) in arr"
            :ref="'myspan' + index">{{index}}:{{item}}</span>
    </div>
</template>

其他问题

返回的是一个proxy对象

let { $refs } = (getCurrentInstance()).proxy;
let dom = $refs['myul'];    //proxy对象
dom.$el;                    //标签内容
dom.$el.clientWidth;        //通过$el即可同getElementById()获取到的标签一样操作
  1. I love it when individuals get together and share views. Great website, keep it up.

  2. Robertmep说道:

    https://gabapharm.com/# cheapest Gabapentin GabaPharm

  3. Log Grapple说道:

    The next time I read a blog, Hopefully it won’t disappoint me as much as this one. After all, I know it was my choice to read through, nonetheless I genuinely believed you’d have something helpful to talk about. All I hear is a bunch of whining about something you could possibly fix if you weren’t too busy seeking attention.

  4. Тут можно преобрести оружейные сейфы и шкафы сейф для сайги 12

  5. DennisBob说道:

    buy gabapentin: Buy gabapentin for humans – gabapentin

  6. Lloydlania说道:

    https://furpharm.com/# cheapest lasix

  7. Can I just say what a relief to find somebody who genuinely understands what they are talking about online. You actually know how to bring a problem to light and make it important. A lot more people must check this out and understand this side of the story. It’s surprising you are not more popular since you surely possess the gift.

  8. Nancy Prentice. For services to the Group in Mid-Glamorgan.

  9. By the late nineteenth century statues had been installed on the esplanade on the northern facet while the streets to the south past Parker Street had been narrow.

  10. My Tattershall Castle one got caught up with a bath towel a number of years ago and one small rip has meant the edges proceed to fray every time that it is washed.

  11. The original design was adapted for numerous applications for use in the 1985 enchantment, each 2D graphics and three-dimensional objects.

  12. Nevertheless, it incurs additional operating prices for amassing every materials, and requires intensive public education to avoid recyclate contamination.

  13. This menagerie craft can isolate modifiers, within the case of getting 3 suffixes, splitting the item will consequence in one copy having 1 suffix, and the opposite having 2, one of many suffixes we’d like shall be assured, however it is a 50/50 to get each suffixes as properly as the open modifier.

  14. Billie Piper continued her function as companion Rose Tyler, for her second and final sequence.

  15. Why we love this game: Truthfully, just because you’ll be able to play it with out utilizing your head a lot, and it all the time creates good laughs as somebody will at all times choose bizarre choices.

  16. In these days, between the personal, nonprofit environmental groups and the world of teams representing business agriculture, collaboration was largely absent.

  17. Ackerman famous that the building ordinance would enable a proper building with masonry partitions over a frame station and reiterated that the rules allow town to power the railroad to do what they need.

  18. Major (now Lieutenant-Colonel) (Technical Officer, Telecommunications) Holroyd Ernest Hugh Clements (105592), Royal Corps of Signals.

  19. The lot rent price and mobile residence park expenses could be slightly troublesome to grasp at first.

  20. CurtisTraup说道:

    buy rybelsus online usa buy rybelsus rybpharm rybpharm cheap semaglutide

  21. Each gem, be it the Manikya, pearl, emerald, or another stone, has its own distinctive options.

  22. Group Captain James Douglas Melvin, OBE.

  23. Just like The Resistance on a surface degree, in Secret Hitler governments take the place of missions, and liberal and fascist policies change successes and failures.

  24. You enter the sphere once, you do all three phases, and then you are executed.

  25. DennisBob说道:

    cheapest lasix: buy lasix fur pharm – lasix

  26. Lloydlania说道:

    https://rybpharm.com/# buy rybelsus rybpharm

  27. The ride is positioned at each Universal Studios Florida and Universal Studios Hollywood in the previous Back to the future: The Journey buildings at each locations.

  28. Grey, Christopher (September 15, 1996).

  29. Lighting specialists plan gentle in very technical terms utilizing site-particular mathematical equations to attain their results.

  30. amg 株価说道:

    Utilizing your nursery crib bedding colors for your foundation will set you in the proper route for the remainder of your decorating needs.

  31. UK – Mid-market private fairness investor LDC has backed the administration buyout (MBO) of Martin Audio, the designer and producer of premium high-efficiency loudspeaker systems, from global audio specialist Loud Audio.

  32. Selwyn Victor Jones, of Point Piper, New South Wales.

  33. fc 掲示板说道:

    “Family farms are just the bottom of the pyramid.

  34. Hobart additionally requested extra particulars from Schneider to offer after the listening to, to Weinberger’s displeasure, noting it was one other delay tactic.

  35. This got here after Wilson cited a regulation from 1873 that at the least four justices (three affiliate and the chief justice) can be required to have the hearing.

  36. Hezekiah Nyaga s/o Njeroge, 1st Grade Tribal Police Constable, Kenya.

  37. Здесь можно преобрести где купить сейф сейф купить в москве

  38. On August 1, 2017, the city Council voted to adopt the ordinance.

  39. Its founder James Melville instructed DeSmog that the marketing campaign, which claims to represent the voices of farmers, plans to target nationwide and native legislation on points like pricing and meals safety as well as “aspects of internet zero”.

  40. You might also get the extra quantity in your subsequent cost in the event you have been assessed as having LCW or LCWRA as part of an ESA declare and also you had been on a ‘credit score-only claim’ while you claimed Common Credit.

  41. Ask for waterfall layers and a rounded perimeter.

  42. The Duchess of Sussex has made headlines along with her dazzling royal tour wardrobe – but her range of hairstyles has been equally noteworthy.

  43. It’s comforting understanding that the extra money is there for me to use in direction of an emergency fund or to go in direction of something special like a down payment on a house or sure, even a brand new car!

  44. Andrew Hyslop Montgomery, Chief Superintendent, Staffordshire Police.

  45. Bus Traces B (Johanesskirche to Haslach Englerplatz) and C (Johanneskirche to St.

  46. 7035 掲示板说道:

    Osborn could not get by means of the door to the aflame ready room.

  47. Step 3: Using white paint, paint a smaller circle (the snowman’s head) resting on top of the bottom circle.

  48. Gummies store说道:

    I really like it when people get together and share ideas. Great website, stick with it.

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注