防抖动函数实际是一个闭包,return出来的function内部有一个setTimeout,初次调用debounce会得到防抖动函数,这里主要说下与vue框架中watch一起使用,debounce不能写在watch函数内部,仔细观察debounce可以发现防抖的关键是定时器的使用和清除,上诉例子中timeout记录当前作用域中是否存在定时器。
<script>
import { debounce } from "../barrage/barrageTool.js";
export default {
name: "recommentProduct",
components: {},
props: {},
data() {
return {
};
},
watch: {
imageMessage: {
handler: function (newValue, oldValue) {
if (this.initShowStatus) {
this.closeRecommentImage();
}
},
deep: true,
},
},
computed: {
//Vuex辅助函数,将公共状态中的属性映射成当前的computed中
...mapState(["imageMessage", "liveManageStatus"]),
},
methods: {
closeRecommentImage: debounce(function () {
this.showFundProduct = false;
if (this.liveManageStatus == 3) {
this.SET_LIVEMANAGESTATUS(0);
}
}, 10000),
},
created() {},
};
</script>
const debounce = (func, wait) => {
let timeout = '';
return (v) => {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
func(v);
}, wait);
}
};