Polymer可以在多个元素之间共享样式

4
我需要在多个Polymer元素之间共享样式。创建一个“styles.html”文件并将其导入到不同的元素中是否可行?随着应用程序的增长,这样做会对性能产生影响吗?我知道在0.5版本中有一个core-styles,但如果导入可以正常工作,它似乎有点不必要。
styles.html
<style>
  button {
    background: red;
  }
</style>

my-button.html

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../styles/main-styles.html">
<link rel="import" href="../behaviors/mixins.html">

<dom-module id="my-button">
  <template>
    <button>{{text}}</button>
  </template>
</dom-module>

<script>
  Polymer({
    is: 'my-button',
    behaviors: [ButtonBehavior]
  })
</script>

你看过样式指南了吗?你可以将常见的样式向下传递到DOM树中。这似乎是一种“干净”的方式,因为它会自动传播。你不必绑定到一个文件(具有特定名称),如果有人忘记导入样式文件或只想使用默认方案,样式也会自动应用。 - Alexander Weber
我确实查看了默认指南。我想我的整个问题只是关于使用imports导入它们是否会有性能影响,还是仅仅是风格偏好的问题。 - Danny Blue
https://dev59.com/RI7ea4cB1Zd3GeqPDZzl - Justin XL
4个回答

7

有关在Chromium中弃用/deep/和::shadow选择器的讨论中建议:

假设您的公共样式保存在名为common-style.css的文件中。

在组件中,您可以使用以下样式标签:

@import url('/common-style.css');

这种方法使您拥有更多控制权:不再将所有样式广播给任何人使用,而是样式消费者必须知道他们需要哪些样式并主动请求它们,这有助于避免冲突。由于浏览器缓存,导入多个样式表没有实际惩罚,事实上,与通过多个影子树级联样式相比,这可能更快。

您可以通过在模板中放置CSS @import来创建一个style.css并在组件中导入它。

由于浏览器在第一个组件加载时缓存它,并从缓存中获取后续组件的样式表,所以不会发生多次网络调用的情况。

我们已经在我们的生产应用程序中使用Web组件了一段时间,采用此技术,因为/deep/已经被弃用,但并没有发现任何显著的性能差异。


2
您可以使用Polymer的共享样式。创建一个包含您样式的文档:
<dom-module id="shared-styles">
  <template>
    <style>
      /* Your styles */
    </style>
  </template>
</dom-module>

然后将此导入到您的元素中,在它们的定义中添加include="shared-styles"<style>标签。


2

通过创建一个dom-module,您可以共享样式,就像其他自定义元素一样。要在自定义元素中包含共享的样式,请使用<style include="style-module-name">。下面是完整的示例。

shared-styles.html

<link rel="import" href="../bower_components/polymer/polymer.html">
<dom-module id="shared-styles">
  <template>
    <style>
      /* CSS goes here */
    </style>
  </template>
</dom-module>

some-element.html

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="shared-styles.html">
<dom-module id="some-element">
  <template>
    <style include="shared-styles">
      /* Element specific styles go here */
    </style>
    <!-- HTML goes here -->
  </template>
  <script>
    Polymer({
      is: 'some-element',
      properties: {
      }
    });
  </script>
</dom-module>

0

从Polymer 1.1开始,Polymer项目的作者建议创建和导入样式模块来解决这个问题。

为了在元素之间共享样式声明,您可以将一组样式声明打包到一个<dom-module>元素中。在本节中,称为样式模块的元素用于保存样式。

样式模块声明了一组命名的样式规则,可以导入到元素定义或自定义样式元素中。

查看更多:https://www.polymer-project.org/1.0/docs/devguide/styling#style-modules


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接