javascript - Vuejs onMounted vs watch ref
问题描述
我想调用一个以 aHTMLElement
作为参数的函数。有问题的元素被渲染为我的页面模板的一部分,所以我需要等待它实际上在 DOM 中。我认为有两种可能的方法可以等待这个元素可见:
- 看着一个
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>
- 使用
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
with ref 而不是调用document.querySelector
.
但我通常更喜欢watch
或watchEffect
等待事物成为某种状态。该onMounted
方法仅在您的模板中没有条件渲染(例如 v-if)时才有效。
性能方面,我认为没有真正的区别。当然,有一个手表,但您的 ref 在其整个生命周期中只更改一次。(如果由于某种原因 el ref 确实发生了变化, onMounted 也不会起作用)
推荐阅读
- laravel - 我的模态引导程序存在但不可见
- javascript - 调用带参数的函数的reactJS渲染无法编译
- python - 检查索引中的任何缺失日期
- google-bigquery - Apache Beam/Google Dataflow PubSub 到 BigQuery 管道:处理插入错误和意外重试行为
- laravel - Laravel 更改存储控制器功能的参数
- spring-boot - Spring Boot 数据源未创建 JNDI
- java - 执行主类时如何使bash自动完成java限定类名
- python - 如何从原始图像尺寸计算内核尺寸?
- java - 抛出 RuntimeException 时,Java 期望返回值
- angular - Azure 广告发现密钥在一段时间后不起作用