<template>
<div>
<input v-model="count" />
</div>
</template>
<script>
import { ref, watch } from "@vue/composition-api";
export default {
setup() {
// 定义响应式数据 count
const count = ref("");
// 异步任务:打印用户输入的关键词
const writeValue = val => {
return setTimeout(() => {
console.log(val);
}, 1000);
};
// 定义 watch 监听
watch(
count,
(newCount, old, clear) => {
// 执行异步任务,并得到关闭异步任务的 id
let id = writeValue(newCount, old);
// console.log(id,old,clear)
// 如果 watch 监听被重复执行了,则会先清除上次未完成的异步任务
clear(() => clearTimeout(id));
},
// watch 刚被创建的时候不执行
{ lazy: true }
);
return {
count
};
}
};
</script>
<style lang="scss" scoped></style>