我正在尝试将聚合物3.0中的.js与html部分分开。
如何在.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函数分离到另一个文件中并进行导入。

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

关于javascript - 如何在Polymer 3中包含外部html文件和js文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52620453/

10-12 00:08
查看更多