spz-action

何时使用

spz-action 用于监听 SPZ 内部 action,并将事件载荷转发给一个或多个目标 action。

当你需要解耦以下角色时可以使用该组件:

  • 事件生产方(例如 spz-product-form
  • 事件消费方(例如渲染组件或 UI 更新组件)

支持布局

  • logic

使用方式

通过配置 action-name 监听内部 action,并在触发时执行 target-action

<spz-action
  action-name="productChange"
  action-scope="#product-section"
  target-action="product-info.update(data=event)">
</spz-action>

代码演示

基本用法

<spz-action
  action-name="productChange"
  target-action="product-info.update(data=event)">
</spz-action>

指定监听范围

<spz-action
  action-name="productChange"
  action-scope="#product-section"
  target-action="product-info.update(data=event)">
</spz-action>

监听多个 action

<spz-action
  action-name="productChange;variantChange"
  target-action="product-info.update(data=event);cart-summary.refresh()">
</spz-action>

属性

属性名说明类型是否必需
action-name要监听的 SPZ action 名称,使用分号分隔多个 action。示例:productChange;variantChangestring
action-scope用于限制 action 监听范围的 CSS 选择器。示例:#product-sectionstring
target-action监听到 action 后执行的目标 action 表达式。示例:product-info.update(data=event)。省略时仅监听不执行后续动作string

Action 表达式示例

<!-- 单个目标 -->
<spz-action target-action="product-info.update(data=event)"></spz-action>

<!-- 多个目标 -->
<spz-action
  target-action="product-info.update(data=event);cart-summary.refresh()">
</spz-action>

<!-- 映射事件字段 -->
<spz-action
  target-action="quantity-input.update(value=event.quantity,max=event.max)">
</spz-action>

工作原理

  1. 组件在构建阶段读取 action-nameaction-scopetarget-action
  2. 组件会对 action-name 中的每个 action 名称分别订阅。
  3. 触发 action 时,会将 event.detail 作为数据上下文传递。
  4. 最终通过 SPZ action service 执行 target-action

端到端示例

<spz-product-form id="product-form-main"></spz-product-form>

<spz-action
  action-name="productChange;variantChange"
  action-scope="#product-section"
  target-action="product-display.update(data=event);price-block.update(data=event)">
</spz-action>

注意事项

  • 该组件本身不暴露自定义 action。
  • 该组件本身不派发新的自定义事件。
  • 在复杂页面中,建议保持 action 命名稳定,避免语义冲突。