Component API
stencil 提供的整个 API 可以浓缩成一组装饰器、生命周期钩子和渲染方法。
装饰器
Decorators are a pure compiler-time construction used by stencil to collect all the metadata about a component, the properties, attributes and methods it might expose, the events it might emit or even the associated stylesheets. Once all the metadata has been collected, all the decorators are removed from the output, so they don't incur any runtime overhead.
- @Component() declares a new web component
- @Prop() declares an exposed property/attribute
- @State() declares an internal state of the component
- @Watch() declares a hook that runs when a property or state changes
- @Element() declares a reference to the host element
- @Method() declares an exposed public method
- @Event() declares a DOM event the component might emit
- @Listen() listens for DOM events
Lifecycle hooks
- connectedCallback()
- disconnectedCallback()
- componentWillLoad()
- componentDidLoad()
- componentShouldUpdate(newValue, oldValue, propName): boolean
- componentWillRender()
- componentDidRender()
- componentWillUpdate()
- componentDidUpdate()
- render()
componentOnReady()
这不是一个在组件类定义中声明的真正的 "生命周期" 方法,而是一个实用方法;它可以用来实现检测你的 Stencil 组件何时完成其第一个渲染周期。
这个方法返回一个 Promise,该 Promise 在第一个渲染周期的 componentDidRender()
之后被调用。
提示
componentOnReady()
在每个组件的生命周期中只解析一次。如果你需要挂钩到后续的渲染周期,请使用 componentDidRender()
或 componentDidUpdate()
。
Executing code after componentOnReady()
resolves could look something like this:
// Get a reference to the element
const el = document.querySelector("my-component");
el.componentOnReady().then(() => {
// Place any code in here you want to execute when the component is ready
console.log("my-component is ready");
});
The availability of componentOnReady()
depends on the component's compiled output type. This method is only available for lazy-loaded distribution types (dist
and www
) and, as such, is not available for dist-custom-elements
output. If you want to simulate the behavior of componentOnReady()
for non-lazy builds, you can implement a helper method to wrap the functionality similar to what the Ionic Framework does here.
appload 事件
除了特定于组件的生命周期钩子之外,当应用及其所有子组件完成加载时,一个名为 appload
的特殊事件将被触发。你可以在 window
对象上监听它。
If you have multiple apps on the same page, you can determine which app emitted the event by checking event.detail.namespace
. This will be the value of the namespace config option you've set in your Stencil config.
window.addEventListener("appload", (event) => {
console.log(event.detail.namespace);
});
Other
Host: Host 是一个函数组件,可以在
render
函数的根节点使用,为宿主元素本身设置属性和事件监听器。h(): 它在
render()
中用于将 JSX 转换为虚拟的 DOM 元素。readTask(): 调度 DOM-read 任务。提供的回调函数将在执行 DOM 读取的最佳时机执行,而不会导致布局混乱。
writeTask(): 调度 DOM-write 任务。提供的回调函数将在执行 DOM 变化的最佳时机执行,而不会导致布局混乱。
forceUpdate(): 即使状态没有改变,也调度给定实例或元素的新渲染。请注意
forceUpdate()
不是同步的,可能在下一帧执行 DOM 渲染。getAssetPath(): 获取本地资源的路径。参考 Assets 页面获取使用信息。
setMode()
getMode()
getElement()