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

/ 2,813评论 / 17540阅读 / 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. MatthewDoolo说道:

    online medication without prescription: buy medication online no prescription – canadian pharmacy without a prescription

  2. MatthewDoolo说道:

    best ed meds online: ed medications online – get ed prescription online

  3. PhilipBup说道:

    cheapest prescription pharmacy cheapest pharmacy to get prescriptions filled pharmacy discount coupons

  4. PhilipBup说道:

    cheap boner pills cheap ed pills discount ed pills

  5. HarveyBeemi说道:

    https://onlinepharmacyworld.shop/# prescription drugs online

  6. HarveyBox说道:

    http://medicationnoprescription.pro/# canadian pharmacy without prescription

  7. Armandosed说道:

    http://edpill.top/# cheapest erectile dysfunction pills

  8. MatthewDoolo说道:

    cheap ed treatment: cheap erectile dysfunction pills – best ed meds online

  9. MatthewDoolo说道:

    where can i buy ed pills: edmeds – best online ed pills

  10. PhilipBup说道:

    online pharmacy reviews no prescription canada drugs without prescription meds online without prescription

  11. PhilipBup说道:

    pharmacy online 365 discount code online pharmacy discount code no prescription pharmacy paypal

  12. DomenicDobby说道:

    how to buy cheap clomid without prescription: can i get clomid prices – can i get generic clomid online

  13. MichaelPycle说道:

    stromectol ivermectin tablets: stromectol tab 3mg – ivermectin humans

  14. BrainSaw说道:

    https://clomida.pro/# buy clomid pills

  15. BrainSaw说道:

    https://clomida.pro/# can you buy cheap clomid without dr prescription

  16. BryanSturf说道:

    amoxicillin 500mg capsule cost: amoxicillin tablet 500mg – amoxicillin online purchase

  17. DomenicDobby说道:

    buy cheap prednisone: prednisone 20 mg pill – 10 mg prednisone tablets

  18. MichaelPycle说道:

    purchase stromectol online: ivermectin 8000 – ivermectin pills

  19. Josephtrink说道:

    http://amoxicillina.top/# amoxicillin buy canada

  20. JamesLot说道:

    zithromax online buy zithromax 500mg online zithromax 500 price

  21. JamesLot说道:

    how to get generic clomid online where can i get cheap clomid without prescription can you get clomid now

  22. MichaelPycle说道:

    can i buy amoxicillin online: amoxicillin cost australia – amoxicillin tablet 500mg

  23. BrainSaw说道:

    https://clomida.pro/# cost cheap clomid now

  24. BrainSaw说道:

    https://prednisonea.store/# prednisone brand name

  25. Josephtrink说道:

    http://clomida.pro/# where can i buy generic clomid without insurance

  26. MichaelPycle说道:

    prednisone 10 mg tablet cost: buy prednisone without prescription – prednisone sale

  27. JamesLot说道:

    where can i buy clomid prices can i purchase cheap clomid without insurance where to get clomid without dr prescription

  28. JamesLot说道:

    buy ivermectin canada minocin 50 mg for scabies ivermectin cost

  29. BrainSaw说道:

    https://prednisonea.store/# can i buy prednisone online without a prescription

  30. BrainSaw说道:

    https://clomida.pro/# buy clomid pills

  31. BryanSturf说道:

    buy amoxicillin 500mg uk: amoxicillin price without insurance – over the counter amoxicillin

  32. MichaelPycle说道:

    50 mg prednisone from canada: prednisone daily – where can i get prednisone over the counter

  33. DomenicDobby说道:

    ivermectin where to buy: minocycline 50 mg tablets online – does minocycline cause weight gain

  34. JamesLot说道:

    generic zithromax india zithromax 250 mg australia zithromax canadian pharmacy

  35. JamesLot说道:

    amoxicillin 50 mg tablets amoxicillin 775 mg amoxicillin 500 mg tablets

  36. BrainSaw说道:

    http://stromectola.top/# ivermectin 3mg price

  37. BrainSaw说道:

    https://amoxicillina.top/# amoxicillin tablet 500mg

  38. MichaelPycle说道:

    buy amoxicillin online mexico: buy amoxicillin online no prescription – amoxicillin without a doctors prescription

  39. Josephtrink说道:

    https://prednisonea.store/# prednisone 5mg cost

  40. DomenicDobby说道:

    order prednisone 10mg: buy prednisone no prescription – prednisone 1 mg daily

  41. BryanSturf说道:

    can you get clomid without dr prescription: generic clomid without insurance – generic clomid without insurance

  42. MichaelPycle说道:

    amoxicillin 250 mg: medicine amoxicillin 500 – amoxicillin cost australia

  43. JamesLot说道:

    ivermectin medication ivermectin otc stromectol price uk

  44. JamesLot说道:

    prednisone 10 mg canada prednisone 10mg tabs prednisone buy canada

  45. Josephtrink说道:

    http://stromectola.top/# ivermectin 12

  46. MichaelPycle说道:

    generic amoxicillin: where can you get amoxicillin – where to buy amoxicillin pharmacy

  47. JamesLot说道:

    zithromax for sale us zithromax over the counter uk zithromax price canada

  48. RussellVeila说道:

    buy ciprofloxacin: ciprofloxacin generic price – buy cipro cheap

  49. Archierut说道:

    https://doxycyclinest.pro/# buy doxycycline monohydrate

  50. Williamzew说道:

    cipro online no prescription in the usa: where can i buy cipro online – cipro

发表回复

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