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

/ 5,964评论 / 33337阅读 / 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. RobertindUp说道:

    apotheke online gГјnstigste online apotheke gГјnstigste online apotheke

  2. RobertindUp说道:

    farmacia barata farmacia online barata y fiable farmacias online seguras

  3. Williamjes说道:

    Farmacie online sicure: farmacia online senza ricetta – Farmacie on line spedizione gratuita

  4. Antoniadat说道:

    farmacia online senza ricetta: farmacia online senza ricetta – Farmacia online più conveniente

  5. RalphRef说道:

    farmacie online autorizzate elenco: farmacie online affidabili – acquistare farmaci senza ricetta

  6. Antoniadat说道:

    pharmacie en ligne: Pharmacie Internationale en ligne – pharmacie en ligne fiable

  7. RobertindUp说道:

    acquistare farmaci senza ricetta farmacie online sicure Farmacia online piГ№ conveniente

  8. RalphRef说道:

    pharmacie en ligne france livraison belgique: pharmacie en ligne avec ordonnance – pharmacie en ligne livraison europe

  9. RobertindUp说道:

    pharmacie en ligne pas cher pharmacies en ligne certifiГ©es pharmacie en ligne

  10. Williamjes说道:

    medikamente rezeptfrei: online apotheke gГјnstig – internet apotheke

  11. Antoniadat说道:

    acquisto farmaci con ricetta: Farmacie online sicure – Farmacie on line spedizione gratuita

  12. Antoniadat说道:

    comprare farmaci online all’estero: migliori farmacie online 2024 – farmacia online senza ricetta

  13. Williamjes说道:

    п»їshop apotheke gutschein: gГјnstigste online apotheke – gГјnstigste online apotheke

  14. RobertindUp说道:

    medikament ohne rezept notfall internet apotheke online apotheke preisvergleich

  15. RobertindUp说道:

    pharmacie en ligne fiable pharmacie en ligne france fiable pharmacie en ligne france livraison internationale

  16. VernonJaf说道:

    http://eufarmacieonline.com/# Farmacie on line spedizione gratuita

  17. Williamjes说道:

    farmacie online autorizzate elenco: farmacia online – Farmacia online piГ№ conveniente

  18. Antoniadat说道:

    online apotheke preisvergleich: online apotheke versandkostenfrei – europa apotheke

  19. Donaldfub说道:

    pharmacie en ligne france livraison belgique: acheter mГ©dicament en ligne sans ordonnance – vente de mГ©dicament en ligne

  20. Antoniadat说道:

    farmacia online envío gratis: farmacia online barata y fiable – farmacia online barata

  21. Williamjes说道:

    pharmacies en ligne certifiГ©es: vente de mГ©dicament en ligne – pharmacie en ligne france fiable

  22. VernonJaf说道:

    https://eufarmacieonline.shop/# top farmacia online

  23. RobertindUp说道:

    ohne rezept apotheke online apotheke preisvergleich online apotheke deutschland

  24. RobertindUp说道:

    Pharmacie sans ordonnance pharmacie en ligne france livraison internationale pharmacies en ligne certifiГ©es

  25. RalphRef说道:

    п»їFarmacia online migliore: Farmacie online sicure – Farmacia online piГ№ conveniente

  26. CharlesOveno说道:

    world pharmacy india indian pharmacy online pharmacy india

  27. Helpful info. Fortunate me I discovered your site accidentally, and I’m surprised why this
    accident did not came about earlier! I bookmarked it.

  28. StevenDouri说道:

    http://36and6health.com/# pharmacy coupons

  29. StevenDouri说道:

    http://36and6health.com/# foreign pharmacy no prescription

  30. Jimmieexake说道:

    https://cheapestmexico.shop/# buying prescription drugs in mexico online

  31. StevenDouri说道:

    https://36and6health.shop/# pharmacy coupons

  32. StevenDouri说道:

    http://cheapestcanada.com/# canadian 24 hour pharmacy

  33. Jimmieexake说道:

    https://cheapestcanada.com/# canadianpharmacyworld

  34. StevenDouri说道:

    https://cheapestindia.shop/# cheapest online pharmacy india

  35. Terrydex说道:

    canadian pharmacy ltd: vipps approved canadian online pharmacy – canadian neighbor pharmacy

  36. CharlesOveno说道:

    п»їbest mexican online pharmacies medicine in mexico pharmacies mexican pharmaceuticals online

  37. StevenDouri说道:

    https://cheapestindia.com/# legitimate online pharmacies india

  38. CharlesOveno说道:

    mail order pharmacy india indian pharmacy online reputable indian online pharmacy

  39. Jimmieexake说道:

    http://cheapestcanada.com/# canadian king pharmacy

  40. StevenDouri说道:

    http://cheapestmexico.com/# mexico drug stores pharmacies

  41. StevenDouri说道:

    http://cheapestcanada.com/# canadian compounding pharmacy

  42. Jimmieexake说道:

    https://cheapestindia.com/# online pharmacy india

  43. StevenDouri说道:

    http://cheapestcanada.com/# certified canadian international pharmacy

  44. StevenDouri说道:

    http://cheapestmexico.com/# mexican pharmaceuticals online

  45. Terrydex说道:

    canadian online pharmacy: cheapestcanada.com – drugs from canada

  46. Terrydex说道:

    ordering drugs from canada: canadian drugs – canadian pharmacy meds review

  47. StevenDouri说道:

    https://cheapestmexico.shop/# mexican border pharmacies shipping to usa

  48. Jimmieexake说道:

    http://cheapestindia.com/# reputable indian online pharmacy

  49. StevenDouri说道:

    https://36and6health.com/# best no prescription pharmacy

发表回复

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