Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] 支持条件指令 #54

Open
cryzzchen opened this issue Apr 19, 2022 · 0 comments
Open

[Feature] 支持条件指令 #54

cryzzchen opened this issue Apr 19, 2022 · 0 comments
Labels

Comments

@cryzzchen
Copy link

cryzzchen commented Apr 19, 2022

使用

新增 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>', []
       ]
  ]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant