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

/ 7,956评论 / 39643阅读 / 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. Jamiescact说道:

    http://indianpharmacyeasy.com/# buy prescription drugs from india

  2. Bradleyarrip说道:

    https://canadiandrugsgate.com/# best drugs for ed

  3. Jefferyswava说道:

    medications list: Canada pharmacy – ed meds online without doctor prescription

  4. LarryHer说道:

    Online medicine order: Indian online pharmacy ship to usa – indian pharmacy paypal

  5. GlennSeade说道:

    indian pharmacy indian pharmacy easy indian pharmacies safe

  6. sugar defender Reviews
    I have actually struggled with blood sugar level changes
    for many years, and it really affected my energy degrees throughout the
    day. Given that starting Sugar Protector, I really feel more well balanced and sharp,
    and I do not experience those afternoon drops anymore!
    I enjoy that it’s a natural remedy that functions without
    any harsh side effects. It’s really been a game-changer for
    me

  7. Jefferyswava说道:

    ed medications online: canadiandrugsgate.com – vitamins for ed

  8. Bradleyarrip说道:

    http://canadiandrugsgate.com/# best male ed pills

  9. Great article. I am dealing with a few of these issues as well..

  10. Introducing to you the most prestigious online entertainment address today. Visit now to experience now!

  11. Jamiescact说道:

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

  12. LarryHer说道:

    mexico pharmacies prescription drugs: mexicanpharmgate.com – medicine in mexico pharmacies

  13. GlennSeade说道:

    best drugs for erectile dysfunction canadiandrugsgate ed symptoms

  14. Jamiescact说道:

    https://indianpharmacyeasy.com/# top 10 online pharmacy in india

  15. Тут можно преобрести шкафы для оружия купить сейф оружейный

  16. Bradleyarrip说道:

    https://indianpharmacyeasy.com/# india pharmacy mail order

  17. Jefferyswava说道:

    pain meds online without doctor prescription: canadiandrugsgate – real cialis without a doctor’s prescription

  18. Jamiescact说道:

    http://indianpharmacyeasy.com/# indian pharmacies safe

  19. LarryHer说道:

    mexican border pharmacies shipping to usa: Mexican Pharm Gate – mexican drugstore online

  20. GlennSeade说道:

    cure for ed Canadian pharmacy online drugs for ed

  21. Bradleyarrip说道:

    http://indianpharmacyeasy.com/# world pharmacy india

  22. Jamiescact说道:

    https://mexicanpharmgate.com/# purple pharmacy mexico price list

  23. Jefferyswava说道:

    levitra without a doctor prescription: canadiandrugsgate – cheap medications

  24. LarryHer说道:

    buy prescription drugs from india: Indian online pharmacy ship to usa – cheapest online pharmacy india

  25. Jefferyswava说道:

    indian pharmacy paypal: indianpharmacyeasy – best online pharmacy india

  26. Jamiescact说道:

    https://mexicanpharmgate.com/# medication from mexico pharmacy

  27. Тут можно преобрести сейф для оружия от производителя купить сейф для пистолета

  28. pink horse cakes说道:

    Stock Evaluation: It has been seen that almost all organizations are not conscious of all the units connected in the collection.

  29. Jamiescact说道:

    https://canadiandrugsgate.com/# ed treatment natural

  30. LarryHer说道:

    how to treat ed: Canada pharmacy – impotance

  31. Bradleyarrip说道:

    https://canadiandrugsgate.com/# medications for ed

  32. Jamiescact说道:

    https://indianpharmacyeasy.com/# top online pharmacy india

  33. Jefferyswava说道:

    mexican border pharmacies shipping to usa: MexicanPharmGate – mexican rx online

  34. You ought to be a part of a contest for one of the highest quality sites on the internet. I most certainly will highly recommend this blog!

  35. Тут можно преобрести сейф москва огнестойкий купить огнестойкие сейфы

  36. Oh my goodness! Amazing article dude! Thanks, However I am experiencing troubles with your RSS. I don’t understand why I cannot join it. Is there anybody else getting the same RSS issues? Anyone that knows the solution can you kindly respond? Thanks!!

  37. RobertCaw说道:

    buy rybelsus rybpharm: buy rybelsus – rybpharm

  38. RobertCaw说道:

    cheapest Gabapentin GabaPharm: cheapest Gabapentin GabaPharm – gabapentin

  39. DennisBob说道:

    buy gabapentin india: buy gabapentin online – buy Gabapentin GabaPharm

  40. CurtisTraup说道:

    ED pills non prescription best ed pill ere pharm ere pharm

  41. I love reading a post that will make people think. Also, thank you for permitting me to comment.

  42. Very nice article. I definitely appreciate this site. Keep it up!

  43. DennisBob说道:

    ere pharm: cheapest ed pills ere pharm – ED meds online

  44. CurtisTraup说道:

    lasix furosemide buy lasix fur pharm

  45. Lloydlania说道:

    https://kampharm.shop/# kampharm shop

  46. 두정오피说道:

    Excellent site you have here.. It’s difficult to find high quality writing like yours nowadays. I honestly appreciate people like you! Take care!!

  47. DennisBob说道:

    ED meds online: erepharm pills – erepharm pills

  48. CurtisTraup说道:

    buy rybelsus rybpharm buy rybelsus rybpharm buy rybelsus rybpharm

发表回复

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