七月上

文章 评论 浏览 29

七月上 2022-05-04 13:57:51

我优化了一下节流的逻辑,保证最后一次必须执行。

function throttle(fn, wait = 500) {
  let canRun = true; // 通过闭包保存一个标记
  let lastTimeId = null; // 纪录最后一次的timeoutId,每次触发回调时都是更新:变为null,或者更新timerId
  return function () {
    clearTimeout(lastTimeId);
    if (canRun) {
      canRun = false;
      setTimeout(() => {
        fn.apply(this, arguments);
        canRun = true;
      }, wait);
    } else {
      lastTimeId = setTimeout(() => {
        fn.apply(this, arguments);
      }, wait);
    }
  };
}
time02004007009001000
canRun

第 3 题:什么是防抖和节流?有什么区别?如何实现?

七月上 2022-05-04 13:56:38
class LazyMan {
	constructor (user) {
		this.timeList = [];
		console.log(`Hi I am ${user}`)
		Promise.resolve().then(res => this.next());
	}
	eat (res) {
		var fn =  () => {
			console.log(`I am eating ${res}`);
			this.next();
		}
		this.timeList.push(fn);
		return this;
	}
	sleep (time) {
		var fn = res => {
			setTimeout(res => {
				console.log(`等待了${time}秒`);
				this.next();
			},time*1000)
		}
		this.timeList.push(fn);
		return this;
	}
	next () {
		var fn = this.timeList.shift();
		fn && fn();
	}
	sleepFrist (time) {
		var fn = res => {
			setTimeout(res => {
				console.log(`先等待了${time}秒`);
				this.next();
			},time*1000)
		}
		this.timeList.unshift(fn);
		return this;
	}
}
function lazyman (res) {
	return new LazyMan(res)
}
_//lazyman('静静').sleep(2).eat('饺子').sleep(3).eat('面').sleepFrist(1).eat('others')
//Hi I am 静静
//先等待了1秒
//等待了2秒
//I am eating 饺子
//等待了3秒
//I am eating 面
//I am eating others_

第 56 题:要求设计 LazyMan 类,实现以下功能

七月上 2022-05-04 13:56:37

原因很简单,一个父组件下不只有你一个子组件。
同样,使用这份 prop 数据的也不只有你一个子组件。
如果每个子组件都能修改 prop 的话,将会导致修改数据的源头不止一处。

所以我们需要将修改数据的源头统一为父组件,子组件像要改 prop 只能委托父组件帮它。从而保证数据修改源唯一

第 40 题:在 Vue 中,子组件为何不可以修改父组件传递的 Prop,如果修改了,Vue 是如何监控到属性的修改并给出警告的

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文