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

/ 4,047评论 / 25440阅读 / 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. RobertLAr说道:

    paxlovid cost without insurance: paxlovid cost without insurance – paxlovid price

  2. 6789bet说道:

    When I initially left a comment I appear to have clicked on the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I receive 4 emails with the exact same comment. Perhaps there is an easy method you can remove me from that service? Many thanks.

  3. You made some really good points there. I looked on the net to find out more about the issue and found most individuals will go along with your views on this site.

  4. 78win说道:

    There is definately a lot to find out about this issue. I really like all of the points you’ve made.

  5. Margarito Genito说道:

    Your style is so unique in comparison to other folks I’ve read stuff from. Many thanks for posting when you’ve got the opportunity, Guess I will just bookmark this blog.

  6. Jamesjer说道:

    where to buy generic clomid pill: how to get cheap clomid without rx – can i purchase cheap clomid without rx

  7. Jamesjer说道:

    buy doxycycline pills online: doxycycline mono – doxycycline medication

  8. Jamesjer说道:

    can i purchase clomid no prescription: can i get generic clomid pill – clomid online

  9. Jamesjer说道:

    can you get generic clomid for sale: cost cheap clomid pills – can you get generic clomid prices

  10. Lanelle Ducos说道:

    Hello, I do believe your web site may be having browser compatibility issues. When I take a look at your blog in Safari, it looks fine however when opening in IE, it’s got some overlapping issues. I just wanted to give you a quick heads up! Apart from that, fantastic blog!

  11. Jamesjer说道:

    doxycycline pills over the counter: buy 40 mg doxycycline – doxycycline hyclate

  12. Jamesjer说道:

    buy ciprofloxacin over the counter: buy ciprofloxacin – cipro 500mg best prices

  13. ThomasInace说道:

    https://clomiddelivery.pro/# can i buy cheap clomid online

  14. Jamesjer说道:

    cost of clomid without dr prescription: can i buy clomid without a prescription – where to buy clomid

  15. ThomasInace说道:

    http://paxloviddelivery.pro/# buy paxlovid online

  16. ThomasInace说道:

    https://doxycyclinedelivery.pro/# price of doxycycline 100mg in india

  17. Jamesjer说道:

    paxlovid generic: paxlovid cost without insurance – paxlovid covid

  18. ThomasInace说道:

    https://clomiddelivery.pro/# order clomid without dr prescription

  19. ThomasInace说道:

    https://amoxildelivery.pro/# can you buy amoxicillin over the counter canada

发表回复

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