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

/ 7,953评论 / 39627阅读 / 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. StevenWearo说道:

    cheap priligy: priligy maxpharm – buy priligy

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

  3. StevenWearo说道:

    prednisone 300mg: generic Prednisone – prednisone 10mg online

  4. Bradleyarrip说道:

    priligy max pharm priligy

  5. Derekjup说道:

    Priligy tablets: priligy maxpharm – priligy maxpharm

  6. Brandenven说道:

    priligy maxpharm: priligy maxpharm – dapoxetine online

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

  8. Brandenven说道:

    prednisone 40 mg daily: buy prednisone – prednisone 30 mg daily

  9. Derekjup说道:

    prednisone coupon: prednisone – prednisone 50 mg tablet cost

  10. StevenWearo说道:

    ampicillin amoxicillin: Amoxicillin Com Pharm – amoxicillin 500 coupon

  11. StevenWearo说道:

    buy cheap amoxicillin online: Amoxicillin for sale – buy amoxicillin 500mg usa

  12. Bradleyarrip说道:

    buy priligy priligy maxpharm buy priligy

  13. Brandenven说道:

    max pharm: buy priligy – Priligy tablets

  14. Brandenven说道:

    can you get clomid online: rex pharm – where buy generic clomid without a prescription

  15. DanielArill说道:

    amoxicillin 500 mg without a prescription http://prednisoneraypharm.com/# buy prednisone tablets online

  16. StevenWearo说道:

    prednisone 20 mg tablets coupon: prednisone ray pharm – order prednisone on line

  17. Derekjup说道:

    amoxicillin generic: Com Pharm – where can you get amoxicillin

  18. Bradleyarrip说道:

    canadian pharmacy amoxicillin amoxicillin 1000 mg capsule amoxicillin 500mg

  19. Узнай все о степени варикоцеле клиника варикоцеле

  20. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали сервисный центр xiaomi в москве, можете посмотреть на сайте: официальный сервисный центр xiaomi
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  21. Derekjup说道:

    buy priligy: priligy max pharm – priligy maxpharm

  22. I seriously love your blog.. Excellent colors & theme. Did you build this website yourself? Please reply back as I’m hoping to create my very own website and would like to know where you got this from or exactly what the theme is named. Thanks.

  23. StevenWearo说道:

    amoxicillin 500 mg where to buy: Amoxicillin for sale – amoxicillin 250 mg price in india

  24. Bradleyarrip说道:

    how to get clomid without a prescription generic clomid buying generic clomid no prescription

  25. 煩わす 例文说道:

    John Phillips Resch, and D’Ann Campbell eds.

  26. And so they don’t seem to get sick of the sight of one another.

  27. Attendees have been leading figures on the earth of engineering and women’s organisations, together with Sir Charles Parsons, Lord Headley, Sir Alfred Yarrow, Mr.

  28. Owen Fitzwilliam Hamilton, Airport Supervisor, Hong Kong Airport.

  29. Brandenven说道:

    can you buy amoxicillin over the counter canada: com pharm – amoxicillin 500mg pill

  30. At about 11 a.m., he saw three college students and a mum or dad leaving the college.

  31. Whereas the 20 per cent figure still represents a relief of 50 per cent in comparison with the usual price, farming unions and opposition parties have criticised the move.

  32. Every difficulty features a reproduction of the complete textual content of the letter in query, supported by varied relevant reference supplies, together with contemporary and modern fiction, academic writing, poetry, and artwork.

  33. Eriksson, Fredrik (2013). “Coping with a brand new Safety State of affairs – Swedish Army Attachés in the Baltic 1919-1939” (PDF).

  34. 迅 とき说道:

    Main-Normal George Alexander Bond, CBE (37433), late Royal Army Service Corps.

  35. 来週 品詞说道:

    Doug Lamborn of Colorado took a small but important step in Congress this week when he introduced a resolution, H. Res.

  36. Style forward and realizing no gender, the deep V takes America by storm.

  37. 彼氏 沼る说道:

    Look to designer present houses, builder show properties, and your garden.

  38. The art of divining is and all the time has been universally diffused.

  39. Elements thought-about in figuring out consistency include, however aren’t limited to, timing of contributions, price of return, priority of returns, and the actual rights of every class of fairness.

  40. レティ 株価说道:

    The lack of resources among struggling households to purchase food is a nationwide problem.

  41. Alleviating Respiratory Issues: It is alleged to assist with respiratory issues like asthma and bronchitis.

  42. “Maps of the contiguous United States launched as a part of the report show precise patterns of farmland loss inside counties,” stated Dr.

  43. Brandenven说道:

    buy priligy max pharm: Priligy tablets – priligy

  44. Baby and Dad and mom magazine have each ranked the museum as the best children’s museum in the United States.

  45. Rear Admiral Anthony Templer Frederick Griffith Griffin.

  46. The Outsider and Others by H.P.

  47. Changing Lighting Hi there Crew: It has been a while.

  48. The essence of organics is brilliantly encapsulated within the Introduction, which begins: “The upkeep of the fertility of the soil is the primary condition of any permanent system of agriculture.” Read on!

发表回复

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