钩子

Owl 钩子 是一种将代码因子化的方式,即使代码依赖于某些组件生命周期。Owl 提供的大多数钩子都与组件的生命周期相关,但其中一些(例如 useComponent)提供了构建特定钩子的方式。

借助这些钩子,可以构建许多定制钩子,用于帮助解决特定问题,或简化某些常见任务。本页其余部分介绍 Odoo Web 框架提供的钩子列表。

名称

简短说明

useAssets

加载资源

useAutofocus

自动聚焦由 autofocus 引用的元素

useBus

订阅和取消订阅事件总线

usePager

显示视图控制面板的分页器。

usePosition

相对于目标定位元素

useSpellCheck

在 input 或 textarea 获得焦点时激活拼写检查

useAssets

库位

@web/core/assets

说明

更多详细信息请参阅 资源懒加载 一节。

useAutofocus

库位

@web/core/utils/hooks

说明

在当前组件中,一旦由 t-ref=”autofocus” 引用的元素出现在 DOM 中且此前未显示过,就聚焦该元素。

import { useAutofocus } from "@web/core/utils/hooks";

class Comp {
  setup() {
    this.inputRef = useAutofocus();
  }
  static template = "Comp";
}
<t t-name="Comp">
  <input t-ref="autofocus" type="text"/>
</t>

API

useAutofocus()
退货

元素引用。

useBus

库位

@web/core/utils/hooks

说明

为总线添加并清除事件监听器。该钩子确保组件卸载时监听器被正确清除。

import { useBus } from "@web/core/utils/hooks";

class MyComponent {
  setup() {
    useBus(this.env.bus, "some-event", event => {
      console.log(event);
    });
  }
}

API

useBus(bus, eventName, callback)
参数
  • bus (EventBus()) – 目标事件总线

  • eventName (string()) – 我们要监听的事件名称

  • callback (function()) – 监听器回调

usePager

库位

@web/search/pager_hook

说明

显示视图控制面板的 分页器。该钩子会正确设置 env.config,以便向分页器提供 props。

import { usePager } from "@web/search/pager_hook";

class CustomView {
  setup() {
    const state = owl.hooks.useState({
      offset: 0,
      limit: 80,
      total: 50,
    });
    usePager(() => {
      return {
        offset: this.state.offset,
        limit: this.state.limit,
        total: this.state.total,
        onUpdate: (newState) => {
          Object.assign(this.state, newState);
        },
      };
    });
  }
}

API

usePager(getPagerProps)
参数
  • getPagerProps (function()) – 返回分页器 props 的函数。

usePosition

库位

@web/core/position_hook

说明

帮助将一个 HTMLElement(即 popper)相对于另一个 HTMLElement(即 reference)进行定位。该钩子确保在窗口缩放/滚动时更新定位。

import { usePosition } from "@web/core/position_hook";
import { Component, xml } from "@odoo/owl";

class MyPopover extends Component {
  static template = xml`
    <div t-ref="popper">
      I am positioned through a wonderful hook!
    </div>
  `;

  setup() {
    // Here, the reference is the target props, which is an HTMLElement
    usePosition(this.props.target);
  }
}

重要

应使用 t-ref 指令 来指定 popper 元素。

API

usePosition(reference[, options])
参数
  • reference (HTMLElement or ()=>HTMLElement()) – 作为定位基准的目标 HTMLElement

  • options (Options()) – 定位选项(见下表)

选项

类型

说明

popper

string

这是用于将被定位元素的 useRef 引用。默认为 "popper"。

container

HTMLElement

popper 预期不会溢出其中的容器。如果发生溢出,则会尝试其他 popper 位置,直到找到不溢出的位置。(默认:<html/> 节点)

margin

数字

popper 与 reference 元素之间增加的边距(默认:0)

position

Direction[-Variant]

期望的位置。它是由一个 Direction 和一个 Variant 组成的字符串,二者以连字符分隔。Direction 可以是:top、bottom、right、left。Variant 可以是:start、middle、end、fit。变体可以省略(默认变体为 middle)。fit 变体表示 popper 将具有与所选方向一致的确切宽度或高度。有效位置示例:right-end、top-start、left-middle、left、bottom-fit。(默认位置:bottom)

onPositioned

(el: HTMLElement, position: PositioningSolution) => void(无返回值)

一个在每次发生定位时都会被调用的回调(例如组件挂载/修补时、文档滚动时、窗口缩放时……)。可用于根据当前位置进行动态样式设置等。PositioningSolution 是一个具有以下类型的对象:{ direction: Direction, variant: Variant, top: number, left: number }。

示例

import { Component, xml, useRef } from "@odoo/owl";
import { usePosition } from "@web/core/position_hook";

class DropMenu extends Component {
  static template = xml`
    <button t-ref="toggler">Toggle Menu</button>
    <div t-ref="menu">
      <t t-slot="default">
        This is the menu default content.
      </t>
    </div>
  `;

  setup() {
    const toggler = useRef("toggler");
    usePosition(
      () => toggler.el,
      {
        popper: "menu",
        position: "right-start",
        onPositioned: (el, { direction, variant }) => {
          el.classList.add(`dm-${direction}`); // -> "dm-top" "dm-right" "dm-bottom" "dm-left"
          el.style.backgroundColor = variant === "middle" ? "red" : "blue";
        },
      },
    );
  }
}

useSpellCheck

库位

@web/core/utils/hooks

说明

在当前组件中,通过 t-ref="spellcheck" 使 input 或 textarea 在获得焦点时激活拼写检查状态。失焦时会移除该状态以及红色边框,从而提升内容的可读性。

该钩子也可用于任何具有 contenteditable 属性的 HTML 元素。要完全禁用可能被该钩子启用的元素上的拼写检查,可在该元素上显式将 spellcheck 属性设置为 false。

示例

在以下示例中,拼写检查将应用于第一个 input、textarea 以及具有 contenteditable="true" 的 div。

import { useSpellCheck } from "@web/core/utils/hooks";

class Comp {
  setup() {
    this.simpleRef = useSpellCheck();
    this.customRef = useSpellCheck({ refName: "custom" });
    this.nodeRef = useSpellCheck({ refName: "container" });
  }
  static template = "Comp";
}
<t t-name="Comp">
  <input t-ref="spellcheck" type="text"/>
  <textarea t-ref="custom"/>
  <div t-ref="container">
    <input type="text" spellcheck="false"/>
    <div contenteditable="true"/>
  </div>
</t>

API

useSpellCheck([options])
参数
  • options (Options()) – 拼写检查选项(见下表)

选项

类型

说明

refName

string

这是用于将被启用拼写检查的元素的 useRef 引用。