Vuejs on Mounted vs手表参考



我想调用一个以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中,这两个都会提供对该元素的引用。为什么其中一个会比另一个更受欢迎?我是不是遗漏了这两种情况中的任何一种会如何发挥作用?最后,是否有理由认为完全不同的解决方案更合适?

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

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

就性能而言,我认为没有真正的区别。当然,有一块手表,但你的裁判在整个生命周期中只改变一次。(如果由于某种原因,如果el ref发生变化,onMounted也不会工作(

将代码更改为如下所示:

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

您还应该查看Vue生命周期挂钩的文档以了解更多信息。

最新更新