首页 > 解决方案 > Vuejs onMounted vs watch ref

问题描述

我想调用一个以 aHTMLElement作为参数的函数。有问题的元素被渲染为我的页面模板的一部分,所以我需要等待它实际上在 DOM 中。我认为有两种可能的方法可以等待这个元素可见:

  1. 看着一个ref
<template><div ref="el"></div></template>
<script>
import {ref, watch} from "vue";
import {exampleFunction} from "example";
export default {
    setup() {
        const el = ref();
        watch(el, (newEl, oldEl) => {
            if (typeof oldEl === "undefined") // Only call function once
                exampleFunction(newEl);
        });
        return {el}
    }
}
</script>
  1. 使用onMounted
<template><div id="el" ref="el1"></div></template>
<script>
import {onMounted, ref} from "vue";
import {exampleFunction} from "example";
export default {
    setup() {
        const el1 = ref();
        onMounted(() => {
            let el2 = document.querySelector("#el"); 
            exampleFunction(el2);
            // OR exampleFunction(el1.value);
        });
        return {el1}
    }
}
</script>

据我所知,一旦元素实际存在于 DOM 中,这两者都会提供对元素的引用。有没有理由为什么其中一个比另一个更受欢迎?我是否错过了这两种情况中的任何一种如何运作的信息?最后,是否有某种理由认为完全不同的解决方案会更合适?

标签: javascriptvue.jsecmascript-6vuejs3vue-composition-api

解决方案


好吧,在您的示例中,两者之间没有区别。您甚至可以使用onMountedwith ref 而不是调用document.querySelector.

但我通常更喜欢watchwatchEffect等待事物成为某种状态。该onMounted方法仅在您的模板中没有条件渲染(例如 v-if)时才有效。

性能方面,我认为没有真正的区别。当然,有一个手表,但您的 ref 在其整个生命周期中只更改一次。(如果由于某种原因 el ref 确实发生了变化, onMounted 也不会起作用)


推荐阅读