lit-html事件侦听器无法正确呈现

时间:2019-03-25 15:51:37

标签: polymer lit-html

我有一个lambda服务,可将html返回给客户端(即浏览器)。但是,事件监听器不起作用。知道为什么吗?代码如下:

const serverless = require('serverless-http');
const express = require('express');
const fetch = require('node-fetch');
const app = express();
app.get('/', function (req, res) {

  var htmlText = `

<!DOCTYPE html>
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.2.7/webcomponents-loader.js"></script>
  <script type="module" >
    import {html, render} from 'https://unpkg.com/lit-html?module';
    /**
     * Adapted from the Ractive.js clock example: http://www.ractivejs.org/examples/clock/
     */
        export class MyElement extends HTMLElement {
          // Define a template
          get flag() { return this._flag; }
          set flag(v) { this._flag = v }

          constructor() {
            super();
            this.attachShadow({mode: 'open'});
            setInterval(() => {
              if (!this.flag) {
                this.flag = true;
                render(this.render(), this.shadowRoot);
              }
            }, 1000);
          }

          // Render the template to the document
          render(site) {
            console.log("called")
            return html\`
              <style>
              :host {
                  display: block;
                  padding: 0 15px;
                  border-right: 1px solid #333333;
                  line-height: 12px;
                }
            </style>
            <button @click="${() => console.log('button was clicked')}">BUTTON</button>
            \`
          }
        }
        customElements.define('my-element', MyElement); 
</script>
</head>
<body>
<p>Hello World</p>
<my-element></my-element>
</body>
</html>
        `;
  res.send(htmlText)
});

module.exports.handler = serverless(app);

从Chrome开发者工具查看shadowroot,该按钮被错误地呈现为<button @click="() => console.log('button was clicked')">BUTTON</button>。知道我在做什么错吗?谢谢。

1 个答案:

答案 0 :(得分:0)

内部阴影dom尝试导入litElement而不是lit-html,因为lit-html使您可以用JavaScript编写HTML模板。

import {html, render} from 'https://unpkg.com/lit-element'

class MyElement extends LitElement {...