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

/ 3,661评论 / 21522阅读 / 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. CharlesOveno说道:

    drugstore com online pharmacy prescription drugs no prescription needed canadian pharmacy cheapest pharmacy to get prescriptions filled

  2. CharlesOveno说道:

    pharmacies in mexico that ship to usa medication from mexico pharmacy mexican rx online

  3. Jimmieexake说道:

    http://cheapestandfast.com/# online no prescription pharmacy

  4. StevenDouri说道:

    https://cheapestcanada.com/# buy prescription drugs from canada cheap

  5. StevenDouri说道:

    https://36and6health.com/# no prescription required pharmacy

  6. StevenDouri说道:

    https://cheapestandfast.shop/# canada pharmacy without prescription

  7. Jimmieexake说道:

    https://cheapestmexico.shop/# pharmacies in mexico that ship to usa

  8. StevenDouri说道:

    https://cheapestindia.shop/# best india pharmacy

  9. CharlesOveno说道:

    top online pharmacy india online shopping pharmacy india india online pharmacy

  10. CharlesOveno说道:

    buy drugs online without prescription cheapest and fast online pharmacy without a prescription

  11. Terrydex说道:

    canada pharmacy reviews: canadian king pharmacy – canadian family pharmacy

  12. Jimmieexake说道:

    https://cheapestmexico.com/# п»їbest mexican online pharmacies

  13. Terrydex说道:

    online pharmacy discount code: no prescription needed pharmacy – canadian online pharmacy no prescription

  14. Marvinmef说道:

    order cheap propecia without insurance cheap propecia cost propecia without a prescription

  15. ThomasTam说道:

    order propecia tablets: buying generic propecia – cost cheap propecia without prescription

  16. ThomasTam说道:

    Abortion pills online: cytotec abortion pill – Abortion pills online

  17. RobertPet说道:

    https://cytotec.xyz/# Cytotec 200mcg price

  18. Marvinmef说道:

    lisinopril 5 mg canada where can i purchase lisinopril where to buy lisinopril online

  19. RobertPet说道:

    http://gabapentin.club/# neurontin pills for sale

  20. ThomasTam说道:

    can i get generic clomid prices: cost of generic clomid pill – can you buy generic clomid price

  21. Marvinmef说道:

    can you get clomid no prescription order generic clomid pills where to get clomid without dr prescription

  22. ThomasTam说道:

    buy cytotec over the counter: cytotec pills buy online – purchase cytotec

  23. Robertguelm说道:

    cytotec buy online usa: buy cytotec over the counter – buy cytotec over the counter

  24. Robertguelm说道:

    order lisinopril online: lisinopril in india – lisinopril tabs 40mg

  25. Marvinmef说道:

    purchase neurontin online buy gabapentin neurontin 100mg tablets

  26. ThomasTam说道:

    neurontin 300 mg caps: order neurontin over the counter – neurontin brand name 800 mg

  27. JamesPouff说道:

    http://clomiphene.shop/# where can i get generic clomid without rx

  28. Marvinmef说道:

    lisinopril tabs 4mg lisinopril 3.5 mg lisinopril 20mg tablets price

  29. ThomasTam说道:

    propecia prices: buying cheap propecia without a prescription – get generic propecia tablets

  30. JamesPouff说道:

    http://lisinopril.club/# prinivil 20 mg tablet

  31. Marvinmef说道:

    cytotec abortion pill cytotec online cytotec buy online usa

  32. RobertPet说道:

    https://lisinopril.club/# purchase lisinopril 10 mg

  33. JamesPouff说道:

    https://propeciaf.online/# cost of cheap propecia without dr prescription

  34. ThomasTam说道:

    cost of generic propecia without rx: get propecia price – buy propecia pill

  35. ThomasTam说道:

    generic propecia prices: propecia pill – propecia pill

  36. JamesPouff说道:

    https://gabapentin.club/# neurontin 300mg

  37. RobertPet说道:

    https://gabapentin.club/# neurontin 100 mg capsule

  38. Marvinmef说道:

    lisinopril diuretic buy lisinopril 20 mg online united states prescription drug lisinopril

  39. Marvinmef说道:

    gabapentin 600 mg neurontin online usa buy neurontin uk

  40. JamesPouff说道:

    https://propeciaf.online/# buying propecia without rx

  41. ThomasTam说道:

    buy misoprostol over the counter: buy cytotec pills online cheap – buy cytotec online fast delivery

  42. ThomasTam说道:

    neurontin online pharmacy: neurontin 300 mg buy – neurontin brand name

  43. Marvinmef说道:

    lisinopril 80 lisinopril tabs 4mg prinivil 25mg

  44. JamesPouff说道:

    https://clomiphene.shop/# where to get cheap clomid price

  45. ThomasTam说道:

    neurontin cost: neurontin 300 mg tablets – neurontin gabapentin

  46. Robertguelm说道:

    lisinopril hctz: lisinopril 2.5 mg medicine – lisinopril from mexico

  47. ThomasTam说道:

    cytotec buy online usa: buy cytotec pills – buy misoprostol over the counter

  48. JamesPouff说道:

    https://clomiphene.shop/# where can i buy generic clomid without insurance

  49. Robertguelm说道:

    neurontin 600 mg capsule: neurontin 200 mg price – neurontin price india

发表回复

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