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

/ 2,568评论 / 13500阅读 / 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. eVisa Online说道:

    It’s enormous that you are getting thoughts from this piece of writing as well as from our discussion made at this time.

  2. JamesAnirm说道:

    https://casinvietnam.shop/# choi casino tr?c tuy?n tren di?n tho?i

  3. MichaelFah说道:

    casino online uy tin game c? b?c online uy tin danh bai tr?c tuy?n

  4. Jesseelell说道:

    http://casinvietnam.com/# danh bai tr?c tuy?n

  5. JamesAnirm说道:

    https://casinvietnam.shop/# casino online uy tin

  6. JoshuaPreri说道:

    web c? b?c online uy tín: web c? b?c online uy tín – casino tr?c tuy?n

  7. Chrisror说道:

    danh bai tr?c tuy?n casino online uy tin casino online uy tin

  8. Chrisror说道:

    choi casino tr?c tuy?n tren di?n tho?i casino tr?c tuy?n vi?t nam game c? b?c online uy tin

  9. Walteronerb说道:

    https://casinvietnam.shop/# danh bai tr?c tuy?n

  10. Walteronerb说道:

    http://casinvietnam.com/# game c? b?c online uy tin

  11. bokep sma说道:

    I really like reading through a post that can make
    men and women think. Also, thank you for permitting
    me to comment!

  12. JoshuaPreri说道:

    casino online uy tín: dánh bài tr?c tuy?n – casino tr?c tuy?n vi?t nam

  13. Chrisror说道:

    casino tr?c tuy?n uy tin game c? b?c online uy tin casino tr?c tuy?n vi?t nam

  14. Chrisror说道:

    danh bai tr?c tuy?n web c? b?c online uy tin game c? b?c online uy tin

  15. MatthewDoolo说道:

    canadian pharmacy online no prescription: buying prescription drugs in india – non prescription canadian pharmacy

  16. AustinWhoto说道:

    online pharmacy canada no prescription: non prescription canadian pharmacy – online pharmacy no prescriptions

  17. MatthewDoolo说道:

    buy meds online no prescription: canadian pharmacy no prescription – online pharmacy without prescription

  18. Armandosed说道:

    https://edpill.top/# ed medications online

  19. PhilipBup说道:

    buy prescription online buy medications online without prescription online pharmacy not requiring prescription

  20. PhilipBup说道:

    prescription drugs canada canadian pharmacy online no prescription buy medication online no prescription

  21. AustinWhoto说道:

    mail order prescription drugs from canada: online pharmacy without prescription – promo code for canadian pharmacy meds

  22. HarveyBox说道:

    https://edpill.top/# ed drugs online

  23. HarveyBeemi说道:

    http://onlinepharmacyworld.shop/# promo code for canadian pharmacy meds

  24. Armandosed说道:

    https://medicationnoprescription.pro/# mexican pharmacy no prescription

  25. MatthewDoolo说道:

    low cost ed meds online: online ed prescription – online ed treatments

  26. MatthewDoolo说道:

    no prescription medicines: medications online without prescriptions – buying online prescription drugs

  27. HarveyBox说道:

    https://onlinepharmacyworld.shop/# canadian pharmacy no prescription needed

  28. Armandosed说道:

    https://edpill.top/# buy erectile dysfunction medication

  29. MatthewDoolo说道:

    cheap erectile dysfunction pills: online ed medication – low cost ed meds online

  30. MatthewDoolo说道:

    mexican pharmacies no prescription: buy pain meds online without prescription – no prescription needed

  31. HarveyBeemi说道:

    http://medicationnoprescription.pro/# canada mail order prescriptions

  32. MatthewDoolo说道:

    canadian pharmacy world coupon code: canadian pharmacy no prescription – canadian pharmacy no prescription needed

  33. PhilipBup说道:

    online pharmacy canada no prescription online drugs without prescription medications online without prescription

  34. PhilipBup说道:

    canadian pharmacy without prescription online pharmacy discount code cheapest pharmacy to fill prescriptions without insurance

  35. AustinWhoto说道:

    cheap ed meds online: edmeds – discount ed meds

  36. MatthewDoolo说道:

    canadian pharmacy no prescription: online pharmacies no prescription – canadian rx prescription drugstore

  37. Armandosed说道:

    https://edpill.top/# ed meds online

  38. HarveyBox说道:

    http://edpill.top/# generic ed meds online

  39. AustinWhoto说道:

    medication online without prescription: online drugstore no prescription – buying prescription drugs online without a prescription

  40. Armandosed说道:

    https://medicationnoprescription.pro/# quality prescription drugs canada

发表回复

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