use:action

  1. use:action
  1. use:action={parameters}
  1. action = (node: HTMLElement, parameters: any) => {
  2. update?: (parameters: any) => void,
  3. destroy?: () => void
  4. }

Actions 是一个元素被创建时会调用的函数集。函数集中的函数会返回一个包含 destroy 的钩子函数的对象,destroy 会在元素被卸载的时候被调用。

  1. <script>
  2. function foo(node) {
  3. // the node has been mounted in the DOM
  4. return {
  5. destroy() {
  6. // the node has been removed from the DOM
  7. }
  8. };
  9. }
  10. </script>
  11. <div use:foo></div>

Action 可以有多个参数,如果返回对象有 update 方法,只要这些参数发生改变,这个方法会在 Svelte 更新标签之后被立即调用。

  1. <script>
  2. export let bar;
  3. function foo(node, bar) {
  4. // the node has been mounted in the DOM
  5. return {
  6. update(bar) {
  7. // the value of `bar` has changed
  8. },
  9. destroy() {
  10. // the node has been removed from the DOM
  11. }
  12. };
  13. }
  14. </script>
  15. <div use:foo={bar}></div>

不用担心如果我们为每个组件实例都重新声明了 foo 会有什么影响—— Svelte 会从组件的定义中移除不依赖于本地状态的函数。