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

/ 3,227评论 / 19331阅读 / 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. ecpp说道:

    Link exchange is nothing else except it is only placing the other person’s web site link on your page at proper place and other person will also do similar in favor of you.

  2. Manuelloupe说道:

    mexican border pharmacies shipping to usa mexico pharmacy mexican pharmacy

  3. Robertswela说道:

    purple pharmacy mexico price list: mexican online pharmacies prescription drugs – purple pharmacy mexico price list

  4. Albertnab说道:

    reputable mexican pharmacies online: buying from online mexican pharmacy – mexico drug stores pharmacies

  5. KennethFobby说道:

    https://mexicanpharmacy1st.shop/# buying prescription drugs in mexico

  6. Robertswela说道:

    medication from mexico pharmacy: best online pharmacies in mexico – buying from online mexican pharmacy

  7. KennethFobby说道:

    https://mexicanpharmacy1st.online/# buying prescription drugs in mexico

  8. Williamlyday说道:

    https://mexicanpharmacy1st.shop/# mexico drug stores pharmacies

  9. Robertswela说道:

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

  10. Albertnab说道:

    mexican border pharmacies shipping to usa: best online pharmacies in mexico – п»їbest mexican online pharmacies

  11. Manuelloupe说道:

    mexico pharmacy mexican drugstore online mexican pharmaceuticals online

  12. Robertswela说道:

    mexican pharmaceuticals online: mexican rx online – mexico pharmacy

  13. Manuelloupe说道:

    mexico drug stores pharmacies mexico drug stores pharmacies mexican rx online

  14. Williamlyday说道:

    http://mexicanpharmacy1st.com/# pharmacies in mexico that ship to usa

  15. Williamlyday说道:

    https://mexicanpharmacy1st.shop/# medicine in mexico pharmacies

  16. Manuelloupe说道:

    purple pharmacy mexico price list medication from mexico pharmacy mexican rx online

  17. Robertswela说道:

    medication from mexico pharmacy: medicine in mexico pharmacies – mexican pharmacy

  18. Robertswela说道:

    mexican pharmacy: pharmacies in mexico that ship to usa – mexico drug stores pharmacies

  19. Albertnab说道:

    reputable mexican pharmacies online: mexican pharmaceuticals online – buying prescription drugs in mexico online

  20. Williamlyday说道:

    https://mexicanpharmacy1st.com/# mexican mail order pharmacies

  21. Williamlyday说道:

    https://mexicanpharmacy1st.com/# mexico drug stores pharmacies

  22. KennethFobby说道:

    https://mexicanpharmacy1st.shop/# medication from mexico pharmacy

  23. Manuelloupe说道:

    mexican pharmacy buying from online mexican pharmacy medicine in mexico pharmacies

  24. KennethFobby说道:

    https://mexicanpharmacy1st.com/# pharmacies in mexico that ship to usa

  25. Robertswela说道:

    purple pharmacy mexico price list: mexico pharmacies prescription drugs – mexico pharmacy

  26. Albertnab说道:

    medication from mexico pharmacy: medication from mexico pharmacy – medication from mexico pharmacy

  27. Thomasliest说道:

    best online pharmacies in mexico: medicine in mexico pharmacies – reputable mexican pharmacies online

  28. Robertswela说道:

    pharmacies in mexico that ship to usa: mexico pharmacies prescription drugs – mexico pharmacies prescription drugs

  29. Thomasliest说道:

    mexico drug stores pharmacies: mexico drug stores pharmacies – buying prescription drugs in mexico

  30. Manuelloupe说道:

    mexico pharmacies prescription drugs medicine in mexico pharmacies mexico drug stores pharmacies

  31. Williamlyday说道:

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

  32. HenryIsona说道:

    zithromax z-pak: zithromax for sale us – zithromax 250mg

  33. Billyeroge说道:

    http://doxycyclinea.online/# where to purchase doxycycline

  34. MarvinMek说道:

    neurontin cost in canada neurontin 300 mg caps neurontin capsule 400 mg

  35. Billyeroge说道:

    https://doxycyclinea.online/# buy cheap doxycycline

  36. MarvinMek说道:

    neurontin 600 mg cost neurontin brand name 800mg best price neurontin cost in singapore

  37. HenryIsona说道:

    doxycycline 100mg tablets: doxycycline order online – doxycycline hydrochloride 100mg

  38. Richardfrota说道:

    generic doxycycline: 100mg doxycycline – how to order doxycycline

  39. MarvinMek说道:

    neurontin canada neurontin cap neurontin 300 600 mg

  40. HenryIsona说道:

    doxycycline hyclate: buy doxycycline online without prescription – buy doxycycline online

  41. Billyeroge说道:

    http://doxycyclinea.online/# 100mg doxycycline

  42. CharlesGib说道:

    neurontin 300 mg pill: neurontin 100mg capsule price – drug neurontin

  43. Billyeroge说道:

    https://prednisoned.online/# prednisone purchase canada

  44. MarvinMek说道:

    order doxycycline online doxycycline hyclate how to buy doxycycline online

  45. CharlesGib说道:

    how much is amoxicillin: amoxicillin 500 coupon – amoxicillin 500mg capsules antibiotic

  46. Richardfrota说道:

    amoxicillin 500 capsule: where to get amoxicillin over the counter – cost of amoxicillin prescription

  47. HenryIsona说道:

    prednisone 50 mg for sale: prednisone 4 mg daily – prednisone 5 mg brand name

  48. MarvinMek说道:

    doxycycline 100mg capsules order doxycycline 100mg without prescription buy doxycycline

  49. HenryIsona说道:

    neurontin generic brand: neurontin 600 – buy generic neurontin

回复 Richardfrota 取消回复

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