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

/ 7,186评论 / 37855阅读 / 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. Williamfug说道:

    best no prescription pharmacy: online pharmacy – legal online pharmacy coupon code

  2. Jeromeviaph说道:

    https://pharmcanada.shop/# canadian discount pharmacy

  3. Donaldkenty说道:

    mexican border pharmacies shipping to usa: mexico drug stores pharmacies – best online pharmacies in mexico

  4. DavidTaK说道:

    safe canadian pharmacy reliable canadian online pharmacy canadian online drugstore

  5. Felipelam说道:

    http://pharmnoprescription.icu/# canadian pharmacy without a prescription

  6. Donaldkenty说道:

    online pharmacy without prescription: cheapest pharmacy – canadian pharmacy no prescription

  7. Jeromeviaph说道:

    https://pharmindia.online/# buy medicines online in india

  8. Felipelam说道:

    http://pharmworld.store/# canadian pharmacy world coupon

  9. DavidTaK说道:

    online meds no prescription buying prescription drugs online without a prescription online pharmacy canada no prescription

  10. DonaldtAg说道:

    canadian pharmacy coupon code: pharm world – best canadian pharmacy no prescription

  11. Williamfug说道:

    mexico drug stores pharmacies: mexican rx online – buying prescription drugs in mexico online

  12. Williamfug说道:

    canada rx pharmacy world: canadian online pharmacy reviews – is canadian pharmacy legit

  13. Felipelam说道:

    https://pharmnoprescription.icu/# canada pharmacy without prescription

  14. Williamfug说道:

    my canadian pharmacy reviews: canadian drug prices – canadian pharmacy 24h com

  15. Williamfug说道:

    canadian online pharmacy: legitimate canadian mail order pharmacy – canada pharmacy 24h

  16. DavidTaK说道:

    mexican drugstore online pharmacies in mexico that ship to usa buying prescription drugs in mexico online

  17. DonaldtAg说道:

    no prescription: buy pills without prescription – can i buy prescription drugs in canada

  18. Felipelam说道:

    http://pharmnoprescription.icu/# online medicine without prescription

  19. DavidTaK说道:

    canadian pharmacy coupon cheapest pharmacy no prescription needed pharmacy

  20. Williamfug说道:

    canadian pharmacy no prescription: pharm world – non prescription medicine pharmacy

  21. Williamfug说道:

    best india pharmacy: pharmacy website india – mail order pharmacy india

  22. DonaldtAg说道:

    mexican rx online: п»їbest mexican online pharmacies – best online pharmacies in mexico

  23. porno film izle说道:

    fantastic points altogether, you simply gained a new reader.
    What could you recommend in regards to your post that you just made a few days in the past?
    Any sure?

  24. DavidTaK说道:

    cheapest online pharmacy india india pharmacy buy prescription drugs from india

  25. Felipelam说道:

    https://pharmmexico.online/# reputable mexican pharmacies online

  26. Felipelam说道:

    http://pharmnoprescription.icu/# online pharmacy that does not require a prescription

  27. DavidTaK说道:

    no prescription needed canadian pharmacy canadian pharmacy discount code canadian pharmacy world coupon

  28. Donaldkenty说道:

    Online medicine order: indian pharmacy paypal – online pharmacy india

  29. Williamfug说道:

    pharmacies in mexico that ship to usa: mexican online pharmacies prescription drugs – mexican pharmacy

  30. Williamfug说道:

    canadian drugstore online: my canadian pharmacy review – trustworthy canadian pharmacy

  31. DavidTaK说道:

    mexican pharmacy mexico drug stores pharmacies mexican pharmaceuticals online

  32. Felipelam说道:

    https://pharmindia.online/# indian pharmacy paypal

  33. DonaldtAg说道:

    canadian pharmacy without prescription: pharm world store – mail order pharmacy no prescription

  34. Felipelam说道:

    https://pharmnoprescription.icu/# canada online prescription

  35. Williamfug说道:

    canadian pharmacy online: pharmacy rx world canada – canadian pharmacy world

  36. DonaldtAg说道:

    pharmacy wholesalers canada: canada pharmacy online – canadian family pharmacy

  37. DavidTaK说道:

    promo code for canadian pharmacy meds online pharmacy canadian pharmacy coupon code

  38. Jeromeviaph说道:

    http://pharmnoprescription.icu/# online canadian pharmacy no prescription

  39. Williamfug说道:

    no prescription online pharmacy: buying prescription drugs in india – online pharmacy without prescriptions

  40. Jeromeviaph说道:

    http://pharmmexico.online/# п»їbest mexican online pharmacies

  41. Felipelam说道:

    http://pharmmexico.online/# mexican rx online

  42. Felipelam说道:

    http://pharmnoprescription.icu/# buying online prescription drugs

  43. Georgefrege说道:

    buy Viagra over the counter: Buy Viagra online cheap – buy Viagra online

  44. Charlesvox说道:

    https://viagras.online/# Sildenafil 100mg price

  45. Elmersoalf说道:

    cialis for sale buy cialis online Buy Tadalafil 10mg

  46. Jamesexite说道:

    Kamagra 100mg price: kamagra oral jelly – cheap kamagra

  47. Elmersoalf说道:

    Cialis without a doctor prescription cialist.pro Cialis over the counter

  48. Jamesexite说道:

    Levitra 20 mg for sale: Levitra 10 mg buy online – Vardenafil online prescription

  49. Charlesvox说道:

    http://cenforce.pro/# Cenforce 150 mg online

  50. Tylerreunk说道:

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

发表回复

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