vue3项目 定时器获取实时时间 检测到dom节点实时增加
<template>
<div>
{{ currentTime }}
</div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
const currentTime = ref('')
onMounted(() => {
setInterval(() => {
currentTime.value = new Date().toLocaleTimeString()
}, 1000);
})
</script>
<style lang="scss" scoped></style>
不知道你这个问题是否已经解决, 如果还没有解决的话:每个组件实例首次被渲染时,首先会生成虚拟dom树,然后根据虚拟dom树创建真实dom,再把真实dom挂载到页面合适的地方,此时,每个虚拟dom树对应一个真实dom
当组件受响应式数据变化的影响,需要重新渲染,就会重新调用render函数,生成一个新的虚拟dom树,然后用新的虚拟dom树跟旧的虚拟dom树做比较,通过对比,vue会找到最小更新量,然后更新必要的虚拟dom节点,最后,这些更新过的虚拟dom节点,会去修改它们对应的真实dom,这样一来,就保证了真实dom的达到了最小的改动
回答:
定时器获取实时时间的问题可以使用Vue 3提供的计算属性computed来解决,只需要对Date对象进行包装即可,代码如下:
<template>
<div>{{ currentTime }}</div>
</template>
<script>
import { computed } from 'vue'
export default {
setup() {
const currentTime = computed(() => {
const time = new Date()
return `${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}`
})
return {
currentTime
}
}
}
</script>
对于检测dom节点实时增加的问题,可以使用Vue 3提供的Composition API中的ref和watch函数进行解决。首先定义一个ref对象来保存需要检查的dom节点,然后使用watch函数监听这个ref对象的变化,当ref对象所代表的dom节点发生变化时,就会触发回调函数执行相应操作。
代码如下:
<template>
<div ref="container"></div>
</template>
<script>
import { ref, watch } from 'vue'
export default {
setup() {
const container = ref(null)
// 监听dom节点变化
watch(container, (newVal, oldVal) => {
// 这里可以写相应的处理逻辑,比如更新数据等
console.log('dom节点发生变化:', newVal, oldVal)
})
return {
container
}
}
}
</script>
以上是针对该问题的解决方案,如果需要了解更多Vue 3相关的优化和技术点,建议查看官方文档和相关教程。