2

我正在尝试创建一个允许我创建 JS 构造函数的简单片段。到目前为止,我所拥有的是

"class constructor": {
    "prefix": "class",
    "body": [
        "class ${1:ClassName} {",
            "\t\tconstructor({${2:thisName}: ${2}}) {",
                "\t\t\tthis.${2} = ${2}",
            "\t}",
        "}"
    ],
    "description": "class constructor template"
},

这按预期工作,但我想看看是否可以添加多个条目,这也this$2{thisName}. 我希望的是能够添加多个键值对。

因此,而不是结束于:

class ClassName {
  constructor({ thisName:  thisName}) {
    this. thisName =  thisName
  }
}

我希望能够添加其他项目,使其看起来像;this.another = another自动创建新行的位置。

class ClassName {
  constructor({ thisName:  thisName, another: another}) {
    this. thisName = thisName
    this.another = another // this is create
 }

}

在这里${3}..不起作用,因为可能有任何数量的项目。

4

1 回答 1

3

尝试这个:

"class constructor": {
  "prefix": "class",
  "body": [

    "class ${1:ClassName} {",
          "\t\tconstructor({${2/([^,]+)([,\\s]*|)/$1: $1${2:+, }/g}}) {",
          "${2/([^,]+)([,\\s]*|)/\t\t\tthis.$1 = $1${2:+\n}/g}",
          "\t}",
      "}"
  ],
  "description": "class constructor template"
},

具有多个调用参数的片段

请参阅我在制作可以使用可变数量参数的 vscode 片段以获得更多解释的答案。

您可以在片段中使用任意数量的参数,只要您在同一个正则表达式捕获组中捕获它们 - 这里每个 arg 都在捕获组 $1 中。

然后每一个都被替换!在你的情况下\t\t\tthis.$1 = $1${2:+\n第二次。在选项卡之后,捕获组用于this.$1 = $1

然后检查捕获组 2 ${2:+\n}。它要么有,,要么什么都没有。如果它有东西,添加一个\n,否则什么都不会添加。

要使此正则表达式起作用,您应该输入参数为

arg1, arg2, arg3, arg4

-- 使用逗号分隔符(逗号后有或无空格)。在您的最后一个参数命中tab触发片段转换之后。

于 2019-10-19T01:29:09.930 回答