Skip to content

[Feature] 支持条件指令 #54

@cryzzchen

Description

@cryzzchen

使用

新增 x-if , x-elseif, x-else 命令。其中 x-elseif 所在元素必须紧跟在 x-ifx-elseif 的元素后面,x-else 所在元素必须紧跟在 x-ifx-elseif 元素后。

SFC 文件:

<template>
  <div x-if={{this.#condition1}} class={{this.#className}}>if {{this.#text}}</div>
  <div x-elseif={{this.#conditin2}}>else if</div>
  <div x-else>else</div>
</template>

运行时用法:

get template() {
  if (this.#condition) {
    return html`<div class=${this.#className}>if ${this.#text}</div>`;
  };
  return html`${this.condition2 ? html`<div>else if</div>` : html`<div>else</div>`}`
}

实现

条件指令编译

规则:

  1. 条件命令所在元素整个替换为 <!--?pwc_c--> 节点;
  2. <!--?pwc_c--> 节点对应的 value 格式为:[ { name: 'if' | 'elseif' | 'else' , value: 条件}, [ 节点模板,节点数据 ] ]

例如上述例子会被编译为以下结构:

  [
      "<!--?pwc_c--><!--?pwc_c--><!--?pwc_c-->",
      [
        [
          {
            name: "if",
            value: this.#condition1
          },
          [ 
            "<!--?pwc_p--><div>if <!--?pwc_t--></div>",
            [
              [{
                name: "class",
                value: this.#className
              }],
              this.#text
            ]
          ]
        ],
        [
          {
            name: "elseif",
            value: this.#condition2
          },
          [
            "<div>else if</div>", []
          ]
        ],
        [
          {
            name: "else"
          },
          [
            "<div>else</div>", []
          ]
        ]
      ]
    ]

运行时嵌套

当 html 发生嵌套时,内部的 html 被认为是一个普通的变量,例如:

// 上面例子中的 html`${this.condition2 ? html`<div>else if</div>` : html`<div>else</div>`}` 当 this.condition2 为 true 时,为:

[
  '<!--?pwc_t-->',
  [
      [
            '<div>elseif</div>', []
       ]
  ]
]

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions