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

/ 7,202评论 / 37899阅读 / 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. Michaelmub说道:

    https://mexicanpharmacy.cheap/# п»їbest mexican online pharmacies

  2. Normancah说道:

    reputable mexican pharmacies online reputable mexican pharmacies online pharmacies in mexico that ship to usa

  3. RaymondLiata说道:

    mexico pharmacy mexican pharmacy mexican rx online

  4. Scottfrurn说道:

    mexico drug stores pharmacies mexican online pharmacies prescription drugs mexican pharmaceuticals online

  5. Coreynuh说道:

    http://mexicanpharmacy.cheap/# п»їbest mexican online pharmacies

  6. StevenGat说道:

    http://cialiskaufen.pro/# online apotheke gГјnstig

  7. ManuelNut说道:

    п»їonline apotheke: Potenzmittel fur Manner – online apotheke versandkostenfrei

  8. RaymondTek说道:

    online apotheke versandkostenfrei Potenzmittel Schneller Besser online apotheke deutschland

  9. Frankencut说道:

    https://potenzmittel.men/# versandapotheke deutschland

  10. StevenGat说道:

    https://cialiskaufen.pro/# online apotheke preisvergleich

  11. RaymondTek说道:

    online apotheke versandkostenfrei online apotheke rezeptfrei versandapotheke deutschland

  12. ManuelNut说道:

    gГјnstige online apotheke: Potenzmittel fur Manner – versandapotheke deutschland

  13. StevenGat说道:

    http://viagrakaufen.store/# Viagra Tabletten für Männer

  14. RaymondTek说道:

    online apotheke preisvergleich Online Apotheke Deutschland online apotheke preisvergleich

  15. Frankencut说道:

    https://potenzmittel.men/# versandapotheke versandkostenfrei

  16. StevenGat说道:

    https://apotheke.company/# online apotheke deutschland

  17. RaymondTek说道:

    versandapotheke kamagra jelly kaufen online apotheke deutschland

  18. Frankencut说道:

    http://kamagrakaufen.top/# online apotheke preisvergleich

  19. RaymondTek说道:

    online apotheke deutschland potenzmittel kaufen online apotheke preisvergleich

  20. StevenGat说道:

    http://viagrakaufen.store/# Sildenafil kaufen online

  21. Eliseokab说道:

    Pharmacie en ligne pas cher: acheter kamagra site fiable – Pharmacies en ligne certifiГ©es

  22. LarryBom说道:

    http://cialissansordonnance.pro/# Pharmacie en ligne fiable

  23. LarryBom说道:

    https://pharmacieenligne.guru/# pharmacie en ligne

  24. MarioRip说道:

    se puede comprar sildenafil sin receta: comprar viagra en espana – п»їViagra online cerca de Madrid

  25. KevinWon说道:

    acheter medicament a l etranger sans ordonnance levitra generique prix en pharmacie pharmacie ouverte 24/24

  26. LarryBom说道:

    http://pharmacieenligne.guru/# Pharmacie en ligne livraison rapide

  27. Eliseokab说道:

    pharmacie ouverte: Pharmacie en ligne livraison 24h – Acheter mГ©dicaments sans ordonnance sur internet

  28. LarryBom说道:

    https://pharmacieenligne.guru/# pharmacie ouverte 24/24

  29. MarioRip说道:

    farmacia online madrid: comprar kamagra en espana – п»їfarmacia online

  30. KevinWon说道:

    Pharmacie en ligne France cialis sans ordonnance Pharmacie en ligne livraison gratuite

  31. LarryBom说道:

    http://pharmacieenligne.guru/# Pharmacie en ligne France

  32. LarryBom说道:

    https://levitrafr.life/# Pharmacie en ligne fiable

  33. LarryBom说道:

    http://cialissansordonnance.pro/# Pharmacie en ligne France

  34. MarioRip说道:

    п»їfarmacia online: gran farmacia online – farmacias online baratas

  35. Eliseokab说道:

    Pharmacie en ligne livraison gratuite: cialis sans ordonnance – acheter mГ©dicaments Г  l’Г©tranger

  36. LarryBom说道:

    http://levitrafr.life/# Pharmacie en ligne France

  37. KevinWon说道:

    Meilleur Viagra sans ordonnance 24h Viagra sans ordonnance pharmacie France Viagra sans ordonnance livraison 24h

  38. LarryBom说道:

    https://cialissansordonnance.pro/# Pharmacie en ligne fiable

  39. LarryBom说道:

    https://viagrasansordonnance.store/# Viagra homme prix en pharmacie

  40. MarioRip说道:

    farmacias online seguras: comprar kamagra – farmacia envГ­os internacionales

  41. LarryBom说道:

    https://pharmacieenligne.guru/# Pharmacie en ligne pas cher

  42. Eliseokab说道:

    pharmacie ouverte 24/24: kamagra oral jelly – Pharmacie en ligne fiable

  43. KevinWon说道:

    pharmacie ouverte kamagra en ligne Pharmacie en ligne pas cher

  44. LarryBom说道:

    https://levitrafr.life/# Acheter médicaments sans ordonnance sur internet

  45. MarioRip说道:

    farmacia online internacional: gran farmacia online – farmacias online seguras

  46. Eliseokab说道:

    Viagra pas cher livraison rapide france: Acheter du Viagra sans ordonnance – Le gГ©nГ©rique de Viagra

  47. LarryBom说道:

    https://kamagrafr.icu/# Pharmacie en ligne livraison 24h

发表回复

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