【问题标题】:How to include external html file and js file in polymer 3?如何在聚合物 3 中包含外部 html 文件和 js 文件?
【发布时间】:2019-03-08 07:05:18
【问题描述】:

我正在尝试将 html 部分与聚合物 3.0 中的 .js 分开。 如何在 .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>
 
    `;
  }

【问题讨论】:

    标签: javascript html web polymer components


    【解决方案1】:

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

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

    index.html

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

    app.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)
    

    home.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 函数。

    app.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)
      })
    

    home.html

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

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

    polymer-skeleton 和这个article

    【讨论】:

      猜你喜欢
      • 2018-04-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多