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

/ 7,964评论 / 39695阅读 / 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. Noel Mackenzie Garrard, Overseas Liaison Officer, National Institute of Agricultural Engineering, Agricultural Analysis Council.

  2. Robertmep说道:

    https://erepharm.com/# ED pills non prescription

  3. The 20 per cent figure nonetheless represents a relief of fifty per cent in comparison with the usual fee.

  4. Lieutenant James Sidney Nobbs (412026), Corps of Royal Engineers.

  5. Use the following pointers to find out what you possibly can handle and what you need to rent out to contractors.

  6. Is there glass that needs replacing?

  7. Main Common Paul Sheldon Bray (448919), late Royal Army Pay Corps.

  8. The corporate had downplayed the time period “Christmas” in much of its advertising for several years.

  9. Flowers work well with fresh country fashion decorating.

  10. DennisBob说道:

    ED pills non prescription: erepharm.com – erepharm.com

  11. CurtisTraup说道:

    ED meds online erepharm pills ere pharm

  12. DennisBob说道:

    furosemide furpharm.com: lasix – furosemide fur pharm

  13. Lloydlania说道:

    http://gabapharm.com/# buy Gabapentin GabaPharm

  14. CurtisTraup说道:

    buy gabapentin cheapest Gabapentin GabaPharm Buy gabapentin for humans

  15. Lloydlania说道:

    https://kampharm.shop/# kamagra oral jelly

  16. After looking at a few of the blog posts on your web page, I honestly like your technique of blogging. I added it to my bookmark website list and will be checking back in the near future. Please check out my web site as well and let me know how you feel.

  17. Robertmep说道:

    http://gabapharm.com/# buy Gabapentin GabaPharm

  18. Ciara说道:

    Good day! Do you know if they make any plugins to assist
    with Search Engine Optimization? I’m trying to get my site to rank for some targeted keywords but I’m not seeing very good gains.
    If you know of any please share. Cheers! I saw similar blog
    here: Eco product

  19. CurtisTraup说道:

    GabaPharm GabaPharm buy Gabapentin GabaPharm

  20. DennisBob说道:

    furosemide furpharm.com: furosemide fur pharm – furosemide fur pharm

  21. DennisBob说道:

    buy rybelsus online usa: rybpharm rybelsus – buy rybelsus canada

  22. 스키강습说道:

    Very good article. I’m dealing with a few of these issues as well..

  23. CurtisTraup说道:

    furosemide fur pharm buy furosemide online cheapest lasix

  24. Good site you have got here.. It’s hard to find excellent writing like yours these days. I really appreciate people like you! Take care!!

  25. CurtisTraup说道:

    erepharm pills ED pills non prescription best ed pills online

  26. DennisBob说道:

    buy rybelsus rybpharm: buy rybelsus rybpharm – rybpharm

  27. DennisBob说道:

    kam pharm shop: kamagra oral jelly – Kamagra Kam Pharm

  28. CurtisTraup说道:

    buy rybelsus rybpharm cheap semaglutide rybpharm

  29. Сервисный центр предлагает ремонт кофемашин ascaso отремонтировать кофемашины ascaso

  30. Howdy! I could have sworn I’ve been to this web site before but after browsing through many of the posts I realized it’s new to me. Regardless, I’m definitely delighted I discovered it and I’ll be book-marking it and checking back often.

  31. Robertmep说道:

    https://rybpharm.com/# buy rybelsus canada

  32. hookup说道:

    I have to thank you for the efforts you have put in writing this site. I really hope to view the same high-grade content by you later on as well. In fact, your creative writing abilities has encouraged me to get my own, personal site now 😉

  33. CurtisTraup说道:

    erepharm pills cheapest ed pills ere pharm ere pharm

  34. Lloydlania说道:

    http://furpharm.com/# buy furosemide online

  35. DennisBob说道:

    buy Gabapentin GabaPharm: gabapentin GabaPharm – GabaPharm

  36. DennisBob说道:

    buy gabapentin online: gabapentin GabaPharm – buy gabapentin india

  37. man说道:

    There is certainly a lot to know about this issue. I really like all the points you’ve made.

  38. CurtisTraup说道:

    buy gabapentin india GabaPharm Gabapentin Buy gabapentin for humans

  39. Lloydlania说道:

    https://kampharm.shop/# kam pharm shop

  40. DennisBob说道:

    cheapest Gabapentin GabaPharm: gabapentin – buy gabapentin india

  41. DennisBob说道:

    erepharm.com: ed pills – ED meds online with insurance

  42. CurtisTraup说道:

    furosemide fur pharm buy furosemide online lasix

  43. Lloydlania说道:

    http://furpharm.com/# buy furosemide online

发表回复

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