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

/ 4,046评论 / 25436阅读 / 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说道:

    Pharmacie sans ordonnance п»їpharmacie en ligne france Pharmacie Internationale en ligne

  2. Antoniadat说道:

    pharmacie en ligne avec ordonnance: pharmacie en ligne sans ordonnance – Pharmacie en ligne livraison Europe

  3. RobertindUp说道:

    medikament ohne rezept notfall п»їshop apotheke gutschein online apotheke gГјnstig

  4. Williamjes说道:

    farmacia online senza ricetta: comprare farmaci online all’estero – comprare farmaci online all’estero

  5. VernonJaf说道:

    https://eumedicamentenligne.com/# Achat mГ©dicament en ligne fiable

  6. Williamjes说道:

    farmacias online baratas: farmacias online seguras – farmacia barata

  7. Antoniadat说道:

    farmacias online seguras: farmacia online envío gratis – farmacias online seguras

  8. RobertindUp说道:

    farmacias online seguras en espaГ±a farmacia online espaГ±a envГ­o internacional farmacias online baratas

  9. Antoniadat说道:

    Farmacia online miglior prezzo: Farmacie online sicure – acquisto farmaci con ricetta

  10. RobertindUp说道:

    pharmacie en ligne pharmacie en ligne france livraison belgique pharmacie en ligne pas cher

  11. VernonJaf说道:

    https://eufarmacieonline.shop/# farmacie online affidabili

  12. Williamjes说道:

    farmacias online seguras: farmacia online madrid – farmacia online barata y fiable

  13. Donaldfub说道:

    pharmacie en ligne pas cher: pharmacies en ligne certifiГ©es – pharmacie en ligne france livraison belgique

  14. Donaldfub说道:

    farmacia online barata y fiable: farmacia online 24 horas – farmacia online barcelona

  15. Williamjes说道:

    farmaci senza ricetta elenco: п»їFarmacia online migliore – migliori farmacie online 2024

  16. Antoniadat说道:

    günstigste online apotheke: beste online-apotheke ohne rezept – günstige online apotheke

  17. RalphRef说道:

    ohne rezept apotheke: eu apotheke ohne rezept – п»їshop apotheke gutschein

  18. Antoniadat说道:

    farmacia barata: farmacia online españa envío internacional – farmacia barata

  19. RobertindUp说道:

    pharmacie en ligne fiable pharmacie en ligne france livraison internationale pharmacies en ligne certifiГ©es

  20. RalphRef说道:

    farmacias online seguras en espaГ±a: п»їfarmacia online espaГ±a – farmacia online barata y fiable

  21. RobertindUp说道:

    comprare farmaci online con ricetta farmacia online Farmacia online miglior prezzo

  22. Williamjes说道:

    farmacia online envГ­o gratis: farmacia online espaГ±a envГ­o internacional – п»їfarmacia online espaГ±a

  23. Antoniadat说道:

    farmaci senza ricetta elenco: farmacia online – acquisto farmaci con ricetta

  24. Williamjes说道:

    pharmacies en ligne certifiГ©es: pharmacie en ligne france fiable – trouver un mГ©dicament en pharmacie

  25. Antoniadat说道:

    farmacie online autorizzate elenco: Farmacia online miglior prezzo – acquisto farmaci con ricetta

  26. RobertindUp说道:

    pharmacie en ligne pharmacie en ligne sans ordonnance pharmacie en ligne sans ordonnance

  27. VernonJaf说道:

    http://eufarmaciaonline.com/# farmacias online seguras en espaГ±a

  28. RobertindUp说道:

    п»їFarmacia online migliore Farmacie on line spedizione gratuita acquistare farmaci senza ricetta

  29. Williamjes说道:

    farmacias online baratas: farmacia online madrid – farmacia online barata

  30. Antoniadat说道:

    farmacias online seguras: farmacia online envío gratis – farmacia online 24 horas

  31. Williamjes说道:

    farmacia online piГ№ conveniente: п»їFarmacia online migliore – Farmacia online miglior prezzo

  32. Antoniadat说道:

    beste online-apotheke ohne rezept: online apotheke preisvergleich – europa apotheke

  33. RobertindUp说道:

    online apotheke gГјnstig medikament ohne rezept notfall ohne rezept apotheke

  34. RalphRef说道:

    pharmacie en ligne france livraison belgique: pharmacie en ligne france fiable – pharmacie en ligne

  35. RobertindUp说道:

    farmacia online madrid farmacia online barcelona farmacia online barata

  36. RalphRef说道:

    beste online-apotheke ohne rezept: internet apotheke – medikamente rezeptfrei

  37. Williamjes说道:

    acquistare farmaci senza ricetta: acquisto farmaci con ricetta – comprare farmaci online all’estero

  38. Antoniadat说道:

    online apotheke deutschland: medikament ohne rezept notfall – medikament ohne rezept notfall

  39. Williamjes说道:

    farmacia online barcelona: farmacia online barata y fiable – farmacia online barcelona

  40. Antoniadat说道:

    günstigste online apotheke: online apotheke – internet apotheke

  41. Donaldfub说道:

    pharmacie en ligne sans ordonnance: acheter mГ©dicament en ligne sans ordonnance – Achat mГ©dicament en ligne fiable

  42. RobertindUp说道:

    Farmacia online miglior prezzo acquisto farmaci con ricetta farmacia online piГ№ conveniente

  43. Donaldfub说道:

    farmaci senza ricetta elenco: Farmacie on line spedizione gratuita – farmaci senza ricetta elenco

  44. It’s not my first time to visit this site, i
    am visiting this site dailly and take good data from
    here every day.

  45. RobertindUp说道:

    trouver un mГ©dicament en pharmacie trouver un mГ©dicament en pharmacie Achat mГ©dicament en ligne fiable

  46. Williamjes说道:

    online apotheke rezept: internet apotheke – gГјnstige online apotheke

  47. VernonJaf说道:

    http://eufarmaciaonline.com/# farmacias online baratas

  48. Antoniadat说道:

    farmacias online seguras: farmacias online seguras – farmacia en casa online descuento

  49. Antoniadat说道:

    Farmacia online miglior prezzo: farmacie online autorizzate elenco – Farmacia online più conveniente

发表回复

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