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

/ 2,788评论 / 17445阅读 / 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. MichaelDaype说道:

    https://wellbutrin.rest/# generic wellbutrin cost

  2. Michaelgew说道:

    ventolin australia buy: ventolin 2mg – buy ventolin tablets uk

  3. JamesImist说道:

    https://mexicopharmacy.store/# buying prescription drugs in mexico online

  4. RobertExozy说道:

    mexican pharmacy testosterone: online pharmacy usa – perscription drugs without perscription

  5. Richardfek说道:

    mexican pharmacies online cheap: cheapest online pharmacy – buying prescription drugs canada

  6. JamesImist说道:

    https://indiapharmacy.site/# indian pharmacies safe

  7. RobertExozy说道:

    top 10 online pharmacy in india: reputable indian pharmacies – best online pharmacy india

  8. Richardfek说道:

    online pharmacies: cheapest online pharmacy – non prescription medicine pharmacy

  9. DanielBriex说道:

    rx prices online pharmacy no prescription canadian drug

  10. JamesImist说道:

    https://ordermedicationonline.pro/# reliable canadian online pharmacy

  11. RobertExozy说道:

    mexico drug stores pharmacies: best online pharmacy – mexico drug stores pharmacies

  12. Vernonnance说道:

    best price for doxycycline: buy doxycycline over the counter – doxycycline 50

  13. Jamesweafe说道:

    https://lisinopril.auction/# over the counter lisinopril

  14. Charlesbaics说道:

    zestoretic 20 12.5 buy lisinopril lisinopril for sale online

  15. Scottbut说道:

    ciprofloxacin generic price: buy ciprofloxacin online – cipro online no prescription in the usa

  16. Scottbut说道:

    buy doxycycline no prescription: doxycycline buy online – doxycycline prescription price

  17. Vernonnance说道:

    cipro 500mg best prices: Buy ciprofloxacin 500 mg online – ciprofloxacin 500mg buy online

  18. Charlesbaics说道:

    best price for lisinopril prescription for lisinopril lisinopril 5 mg tablet cost

  19. Jamesweafe说道:

    http://ciprofloxacin.men/# buy cipro online canada

  20. Scottbut说道:

    generic zithromax online paypal: zithromax z-pak – zithromax 500mg

  21. Charlesbaics说道:

    lisinopril 10 mg no prescription buy lisinopril online buy cheap lisinopril

  22. Jamesweafe说道:

    http://ciprofloxacin.men/# buy ciprofloxacin over the counter

  23. Vernonnance说道:

    zithromax 500 tablet: buy zithromax canada – zithromax 250

  24. Scottbut说道:

    zithromax price south africa: zithromax antibiotic without prescription – where can i get zithromax over the counter

  25. Jamesweafe说道:

    https://doxycycline.forum/# doxycycline 100 mg coupon

  26. Scottbut说道:

    amoxicillin 500mg: where can i buy amoxicillin online – amoxicillin in india

  27. Charlesbaics说道:

    amoxicillin tablets in india buy amoxil amoxicillin 500mg over the counter

  28. Vernonnance说道:

    buy amoxicillin canada: where can i get amoxicillin 500 mg – buying amoxicillin online

  29. Jamesweafe说道:

    http://lisinopril.auction/# cost of lisinopril 10 mg

  30. Scottbut说道:

    prices for lisinopril: Buy Lisinopril 20 mg online – lisinopril 20 mg tablet cost

  31. JosephBut说道:

    sildenafil for sale canada: sildenafil prescription cost – sildenafil 100mg generic

  32. WilliamTut说道:

    http://kamagra.team/# Kamagra 100mg price

  33. Timothykew说道:

    canada tadalafil generic: tadalafil online in india – 60 mg tadalafil

  34. RichardMus说道:

    tadalafil cheap tadalafil generic otc best online tadalafil

  35. Juliuselinc说道:

    http://levitra.icu/# Vardenafil online prescription

  36. Timothykew说道:

    Kamagra 100mg price: super kamagra – buy Kamagra

  37. RichardMus说道:

    tadalafil tablet buy online canadian pharmacy tadalafil where can i get tadalafil

  38. Juliuselinc说道:

    http://levitra.icu/# Generic Levitra 20mg

  39. JosephBut说道:

    tadalafil 20mg canada: buy tadalafil india – generic tadalafil without prescription

  40. WilliamTut说道:

    http://kamagra.team/# Kamagra tablets

  41. Timothykew说道:

    Kamagra 100mg price: п»їkamagra – buy kamagra online usa

  42. RichardMus说道:

    sildenafil in india online generic sildenafil sildenafil pills

  43. Juliuselinc说道:

    https://kamagra.team/# Kamagra 100mg price

  44. Timothykew说道:

    sildenafil oral jelly 100mg kamagra: sildenafil oral jelly 100mg kamagra – buy Kamagra

  45. RichardMus说道:

    Kamagra 100mg price Kamagra Oral Jelly п»їkamagra

  46. JosephBut说道:

    sildenafil oral jelly 100mg kamagra: sildenafil oral jelly 100mg kamagra – buy kamagra online usa

  47. Juliuselinc说道:

    http://sildenafil.win/# order sildenafil 100mg

  48. WilliamTut说道:

    http://kamagra.team/# cheap kamagra

  49. Timothykew说道:

    buy cheap tadalafil online: tadalafil online cost – canadian pharmacy tadalafil

发表回复

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