Vue3 传参防抖简单使用
动态传递子组件数据 使用TypeScript来封装防抖函数
Vue3 动态传参使用
- 在 script setup 中定义要传递的数据,例如:
1 2 3 4
| <script setup> import { ref } from 'vue' const message = ref('Hello world') </script>
|
- 在 template 中使用 render 函数来创建一个子组件,并将数据作为 props 传递给它,例如:
1 2 3 4 5
| <template> <div> <子组件 :message="message" /> </div> </template>
|
- 在子组件中,使用 defineProps 来接收 props,并在 template 中使用它们,例如:
1 2 3 4 5 6 7 8 9 10
| <script setup> import { defineProps } from 'vue' const props = defineProps({ message: String }) </script>
<template> <div>{{ message }}</div> </template>
|
TypeScript 防抖函数
短时间内回调方法不允许被调用
- 定义一个函数 debounce,它接受一个回调函数 fn 和一个延迟时间 delay 作为参数,返回一个新的函数:
1 2 3 4 5 6 7 8 9 10 11 12
| function debounce(fn: Function, delay: number) { let timer: number | null = null return function(...args: any[]) { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { fn(...args) timer = null }, delay) } }
|
参考文档