html 注入带参数的调用函数

html inject call function with parameter

我有一个问题,如果我想向我的 click 属性添加一个参数,那么它会在它呈现后立即调用该函数

这是我的测试html:

return html`
       <button class="menu-btn" @click="${this._OpenSubMenu(1)}>test</button>" 
`;

}

以及函数:

_OpenSubMenu(test:number) {
    console.log("Hello")
  }

页面一呈现就输出Hello

那么如何在向我的函数添加参数的同时避免这种情况呢?

您需要使函数 return 成为一个函数。然后您的点击函数将执行 returned 函数,并且由于闭包仍然可以访问参数。

例如..

_OpenSubMenu(test:number) {
  var that = this;
  return function () {
     console.log("Hello");
     //test is also a closure so you can use here
     //that will equal this
  }
}

如果你想访问this,你也可以使用箭头函数

_OpenSubMenu(test:number) {
  return () => {
     console.log("Hello");
     //test is also a closure so you can use here
     //this will also still be valid here
  }
}