有时你需要在组件更新之后做一些事情。例如,你可能需要在更新后测量组件,以便执行命令式操作(如动画)。有一个回调可以做到这一点,毫不意外它叫做 updated()

右侧的组件在你点击按钮时会显示一条消息。不过这并不怎么令人兴奋。它可以使用某种过渡效果。

在组件中添加以下 updated() 方法:

protected updated(changedProperties: PropertyValues<this>): void {
if (changedProperties.has('_showMessage')) {
const final = this._message.getBoundingClientRect().width;
const starting = 0 - final;
var player = this._message.animate([
{ transform: `translateX(${starting}px)` },
{ transform: `translateX(0)` }
], {
duration: 500,
easing: 'ease-out',
});
}
}
updated(changedProperties) {
if (changedProperties.has('_showMessage')) {
const final = this._message.getBoundingClientRect().width;
const starting = 0 - final;
this._message.animate([
{ transform: `translateX(${starting}px)` },
{ transform: `translateX(0)` }
], {
duration: 500,
easing: 'ease-out',
});
}
}

这不是实现这种特定动画最简单的方式,但它演示了如何在更新后测量 DOM,这对于许多动画来说是一项关键任务。

需要添加动画?

你可以使用 CSS 添加简单的动画。对于更复杂的动画,@lit-labs/motion 包可以提供帮助。示例代码请参阅 Playground 中的 motion 示例

updated() 回调与其他更新周期回调的不同之处在于,在 updated() 期间发生的响应式属性更新触发新的更新。