面试题答案
一键面试1. beforeUpdate 和 afterUpdate 生命周期函数协同工作原理
- beforeUpdate:在组件的状态或属性发生变化,DOM 即将更新之前触发。这是一个在 DOM 更新前执行一些准备工作的好时机,比如记录旧的状态值,为即将到来的更新做一些计算等。
- afterUpdate:在组件的 DOM 已经更新完毕后触发。此时,新的状态已经反映在 DOM 上,可以进行依赖于新 DOM 状态的操作,例如操作新生成的 DOM 元素,重新初始化第三方库等。
2. 父组件更新触发子组件更新时的执行顺序
- 父组件:父组件状态变化触发
beforeUpdate
。 - 子组件递归:从最外层父组件开始,向下递归到最内层子组件,依次触发子组件的
beforeUpdate
。 - DOM 更新:所有组件的
beforeUpdate
执行完毕后,Svelte 开始更新 DOM。 - 子组件递归:从最内层子组件开始,向上递归到最外层父组件,依次触发子组件的
afterUpdate
。 - 父组件:父组件的
afterUpdate
最后执行。
3. 代码示例
假设我们有一个父组件 Parent.svelte
和一个子组件 Child.svelte
。
Child.svelte
<script>
let count = 0;
$: console.log('Child: before component state update, count is', count);
const handleClick = () => {
count++;
};
$: console.log('Child: after component state update, count is', count);
console.log('Child: initial load');
let localValue;
// beforeUpdate 生命周期函数
$: {
if (count > 0) {
localValue = 'Some complex calculation based on new count value';
}
}
// afterUpdate 生命周期函数
$: {
if (count > 0) {
const newDiv = document.createElement('div');
newDiv.textContent = localValue;
document.body.appendChild(newDiv);
}
}
</script>
<button on:click={handleClick}>Increment in Child</button>
<p>Child count: {count}</p>
Parent.svelte
<script>
import Child from './Child.svelte';
let parentCount = 0;
$: console.log('Parent: before component state update, parentCount is', parentCount);
const handleParentClick = () => {
parentCount++;
};
$: console.log('Parent: after component state update, parentCount is', parentCount);
console.log('Parent: initial load');
// beforeUpdate 生命周期函数
$: {
if (parentCount > 0) {
console.log('Parent: Complex data processing before update');
}
}
// afterUpdate 生命周期函数
$: {
if (parentCount > 0) {
console.log('Parent: DOM manipulation after update');
}
}
</script>
<button on:click={handleParentClick}>Increment in Parent</button>
<p>Parent count: {parentCount}</p>
<Child />
在这个示例中,当点击父组件的按钮时,父组件的 beforeUpdate
先执行,然后子组件的 beforeUpdate
执行。DOM 更新后,子组件的 afterUpdate
先执行,最后父组件的 afterUpdate
执行。通过 beforeUpdate
进行复杂数据处理,afterUpdate
进行 DOM 操作。