生命周期
onMount
在组件首次渲染到 Dom 后立即触发的函数
onDestroy
在组件销毁时触发的函数,主要用来做一些清理
beforeUpdate 和 afterUpdate
beforeUpdate 函数会在 DOM 更新之前执行,而相应的 afterUpdate 则在数据同步到 DOM 之后执行
对于强制执行那些仅以状态驱动的方式却难以实现的事情非常有用,例如更新元素的滚动位置
beforeUpdate(() => {
autoscroll = div && div.offsetHeight + div.scrollTop > div.scrollHeight - 20;
});
afterUpdate(() => {
if (autoscroll) div.scrollTo(0, div.scrollHeight);
});
tick
在数据变化的时候,组件并不会立即开始更新,而是在等待下一个微任务的时候再更新 dom,所以,当你想立刻获得组件数据是不成功的,官方例子
app.svelte
<script>
let text = `Select some text and hit the tab key to toggle uppercase`;
async function handleKeydown(event) {
if (event.which !== 9) return;
event.preventDefault();
const { selectionStart, selectionEnd, value } = this;
const selection = value.slice(selectionStart, selectionEnd);
const replacement = /[a-z]/.test(selection)
? selection.toUpperCase()
: selection.toLowerCase();
text =
value.slice(0, selectionStart) + replacement + value.slice(selectionEnd);
await tick();
this.selectionStart = selectionStart;
this.selectionEnd = selectionEnd;
}
</script>
<style>
textarea {
width: 100%;
height: 200px;
}
</style>
<textarea value="{text}" on:keydown="{handleKeydown}"></textarea>
当然也可以通过 settimeout,或者在 afterupdate 中来实现,但是这样的开销就大了,仁者见仁,智者见智