【问题标题】:Vuejs onMounted vs watch refVuejs onMounted vs watch ref
【发布时间】:2021-07-16 01:53:37
【问题描述】:

我想调用一个以HTMLElement 作为参数的函数。有问题的元素被呈现为我的页面模板的一部分,所以我需要等待它实际位于 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 中,它们都会提供对元素的引用。有没有理由为什么其中一个比另一个更受欢迎?我是否错过了这两种情况中的任何一种如何运作的信息?最后,有什么理由认为完全不同的解决方案更合适?

【问题讨论】:

  • 较少使用watch 可能会提高性能?如果只使用一次,还有什么理由继续观看?有一块只做一件事的手表可能会很昂贵。
  • 这点很好,没有考虑资源影响
  • 为什么不在mounted中使用this.$refs.el。不用看。
  • @MichaelMano 我的意思是,当然,您可以在 onMounted 调用中使用 ref,但是,我认为这与 document.querySelector 并没有太大的不同。也就是说,手表与已安装基本上是我的全部问题!
  • 是的,我理解你的问题,更多的是我自己的问题。是的,看 el 有点毫无意义,因为你只需要它一次。安装。 $refs 也有更好的性能。

标签: javascript vue.js ecmascript-6 vuejs3 vue-composition-api


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    将您的代码更改为如下所示:

    <template>
      <div id="el"></div>
    </template>
    
    <script>
    export default {
      mounted() {
        let el = document.querySelector("#el");
    
        exampleFunction(el);
    
        return {el}
        }
    }
    </script>
    

    您还应该查看 Vue Life Cycle Hooks 的文档以获取更多信息。

    【讨论】:

    • 我认为您的代码与 OP 的第二种方法相同,只是他使用的是 Vue 3 的 setup 选项。
    • mountedonMounted 相同。我正在使用Composition API
    猜你喜欢
    • 2022-01-20
    • 2021-07-07
    • 2016-12-26
    • 2011-06-27
    • 2021-05-04
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 2010-12-03
    相关资源
    最近更新 更多