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

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

    buy amoxicillin 500mg canada http://prednisoneraypharm.com/# prednisone cream

  2. 21, 1999? Nasdaq gives info of company’s quick interest and the common days it takes to cover them.

  3. No sympathy for agri buyers, although.

  4. Financing is assured by a 3.5 billion euro subsidy made possible by way of transportation deposits paid by corporations and contributions from public group groups.

  5. William David Peirse, Headmaster, St Aidan’s Church of England Highschool, Preesall, Blackpool, Lancashire.

  6. There is no such thing as a room for compromise with this.

  7. American turquoise additionally has spider net-like matrix on the surface making it look completely different from those seen on natural Irani firoza stone.

  8. After delivering an emergency food box to Mike, a handicapped Vietnam veteran, Phil noticed the condition of his shoes.

  9. Firoza has some mere connections with disease curing as properly and helps in controlling blood strain, correct functioning of the nervous system and fights well against several harmful disorders.

  10. 漫画 サロン说道:

    A: Pure Irani Firoza is primarily utilized in jewellery, corresponding to rings, earrings, and pendants.

  11. This Christmas exercise will show you ways.

  12. So what else has McGee been in?

  13. StevenWearo说道:

    prednisone 20mg online: raypharm – prednisone in uk

  14. ‘divine or astronomical Dynasties,’ who taught the Third Root-Race; and after having abandoned the Atlanteans to their doom, returned (or redescended, rather) through the third Sub-Race of the Fifth, with a purpose to reveal to saved humanity the mysteries of their beginning-place – the sidereal Heavens.

  15. 最強の投資说道:

    Pop stars and boy bands begin many trends.

  16. 安濃sa下り说道:

    Waksman writes originally: “A information of soil humus is most important for a proper understanding of the origin and nature of the soil as well as of the processes that management plant progress” (p.4).

  17. Free online video games to play with friends1.

  18. Figuring out your goal is the crux of any funding – your place to begin.

  19. The fact is, that after you have stained a tea towel, you may attempt biological washing powders, boiling, stain remover or fancy tips with vinegar; all these strategies will impact the quality, and longevity, of your tea towel and may never remove the stain.

  20. まよ晴れ说道:

    The couple’s pal John Ellis officiated the ceremony.

  21. Squadron Chief Clifford Philpot (51156), Royal Air Power; currently on mortgage to the federal government of Pakistan.

  22. According to Web page Six, the 57-year-outdated speak present host settled on a Jeffrey Rackover wedding ceremony band set with two carats of pavé diamond.

  23. StevenWearo说道:

    amoxicillin buy online canada: com pharm – amoxicillin 500mg without prescription

  24. DanielArill说道:

    purchase amoxicillin 500 mg https://priligymaxpharm.com/# buy priligy

  25. Brandenven说道:

    cost clomid tablets: generic clomid – where can i buy clomid without rx

  26. Brandenven说道:

    can i purchase clomid: rex pharm – clomid otc

  27. Derekjup说道:

    rexall pharmacy amoxicillin 500mg: buy amoxil online – amoxicillin tablet 500mg

  28. StevenWearo说道:

    how to get prednisone without a prescription: prednisone – how can i get prednisone online without a prescription

  29. DanielArill说道:

    how to buy amoxycillin http://prednisoneraypharm.com/# prednisone 12 tablets price

  30. Bradleyarrip说道:

    how to buy generic clomid for sale can you buy generic clomid online can i order generic clomid without dr prescription

  31. ShaunLolve说道:

    pills for ed http://canadiandrugsgate.com/# buy anti biotics without prescription
    buy ed drugs

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

  33. LarryHer说道:

    india pharmacy: Indian pharmacy international shipping – india pharmacy

  34. Jefferyswava说道:

    indian pharmacy paypal: Best online Indian pharmacy – pharmacy website india

  35. GlennSeade说道:

    Online medicine home delivery Indian pharmacy to USA india pharmacy

  36. LarryHer说道:

    mexico pharmacies prescription drugs: mexican pharmacy online medications – reputable mexican pharmacies online

  37. Jefferyswava说道:

    indian pharmacy paypal: Best Indian pharmacy – Online medicine order

  38. Здесь можно преобрести заказать сейф купить сейф в москве

  39. I love reading an article that can make men and women think. Also, thank you for allowing for me to comment.

  40. LarryHer说道:

    male enhancement products: canadian drugs gate – erectal disfunction

  41. Jefferyswava说道:

    discount prescription drugs: canadiandrugsgate.com – how can i order prescription drugs without a doctor

  42. Bradleyarrip说道:

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

  43. Jefferyswava说道:

    indian pharmacies safe: indianpharmacyeasy – buy prescription drugs from india

  44. GlennSeade说道:

    treating ed Canadian pharmacy online ed therapy

  45. Bradleyarrip说道:

    http://mexicanpharmgate.com/# mexican pharmaceuticals online

  46. LarryHer说道:

    Online medicine order: Indian online pharmacy ship to usa – online shopping pharmacy india

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

  48. 동대구오피说道:

    This website was… how do you say it? Relevant!! Finally I’ve found something which helped me. Thanks a lot.

  49. Jamiescact说道:

    http://canadiandrugsgate.com/# dog antibiotics without vet prescription

发表回复

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