繁体   English   中英

如何在聚合物 3 中包含外部 html 文件和 js 文件?

[英]How to include external html file and js file in polymer 3?

我正在尝试将 html 部分与 .js 中的polymer 3.0 分开。 如何在 .js 中包含外部 html 文件? 或者我怎样才能将它们分开?

 import {html, PolymerElement} from '@polymer/polymer/polymer-element.js'; /** * @customElement * @polymer */ class InfyAssign extends PolymerElement { static get template() { return html` <style> :host { display: block; } </style> <div class="row"> <div class="col-md-3"> Hello </div> <div> <img src="../../images/image1.jpg"> </div> </div> `; }

首先,我不建议您将 html 部分分离到另一个文件。 如果您觉得您的组件太大,只需将其与另一个组件分开即可。

因为它是一个 javascript 文件(ES6 模块)所以它不能直接导入 html 但你可以将template函数分离到另一个文件并导入它。

索引.html

<my-app></my-app>
<script type='module' src='app.js'></script>

应用程序.js

import { PolymerElement } from '@polymer/polymer/polymer-element.js'
import home from './home.js'

class App extends PolymerElement {
  static get properties () {
    return {
      count: Number
    }
  }

  static get template () {
    return home()
  }

  constructor () {
    super()
    this.count = 0
  }

  increaseCount () {
    this.count += 1
  }
}

customElements.define('my-app', App)

主页.js

import { html } from '@polymer/polymer/polymer-element.js'

export default function () {
  return html`
    <h1>Home</h1>
    <h2>Count: {{count}}</h2>
    <button on-click='increaseCount'>Increase</button>
  `
}

如果你想要一个真正的html文件。 您可以使用fetch下载 html 文件并将其解析为template函数。

应用程序.js

import { PolymerElement, html } from '@polymer/polymer/polymer-element.js'

class App extends PolymerElement {
  static get properties () {
    return {
      count: Number
    }
  }

  constructor () {
    super()
    this.count = 0
  }

  increaseCount () {
    this.count += 1
  }
}

fetch('home.html')
  .then(response => response.text())
  .then(text => {
    Object.defineProperty(App, 'template', {
      get: function () {
        return eval(`html\`${text}\``)
      }
    })
    customElements.define('my-app', App)
  })

主页.html

<h1>Home</h1>
<h2>Count: {{count}}</h2>
<button on-click='increaseCount'>Increase</button>

或者您可以使用像 Webpack 这样的包库,它允许您将 html 文件(通过加载程序)导入到您的 javascript 文件中。

聚合物骨架和这篇文章

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM