【问题标题】:How to dynamically inject styles in Nuxt?如何在 Nuxt 中动态注入样式?
【发布时间】:2020-02-25 15:23:42
【问题描述】:

在使用 WordPress 构建 Nuxt 应用程序时,我正在从 WordPress API 导入自定义 css。

如何将自定义 CSS 注入模板?

<template>
  <div class="container">
    <style>
      {{ content.custom_css }} 
    </style>
    <div class="wordvue mt-5" v-html="content.rendered"></div>
  </div>
</template>

我的问题是这在开发模式下工作,但是在生产模式下样式标签被删除了。

有什么解决办法吗?

【问题讨论】:

    标签: javascript vue.js vuejs2 nuxt.js


    【解决方案1】:

    &lt;style&gt; 编译时会自动去除标签。幸运的是 tmorehouse 通过使用 Vue 的 &lt;component&gt;

    提供了一个解决方案
    <template>
      <div>
        <component is="style">
          .foo[data-id="{{ uniqueId }}"] {
            color: {{ color }};
          }
          .foo[data-id="{{ uniqueId }}"] .bar {
            text-align: {{ align }}
          }
        </component>
        <div class="foo" :id="id" :data-id="uniqueId">
          <div class="bar">
          </div>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      props: {
        id: {
          type: String,
          default: null
        }
      },
      computed: {
        uniqueId() {
          // Note: this._uid is not considered SSR safe though, so you
          // may want to use some other ID/UUID generator that will
          // generate the same ID server side and client side. Or just
          // ensure you always provide a unique ID to the `id` prop
          return this.id || this._uid;
        },
        color() {
          return someCondition ? 'red' : '#000';
        },
        align() {
          return someCondition ? 'left' : 'right';
        }
      }
    }
    </script>
    

    查看https://forum.vuejs.org/t/about-using-style-tags-inside-templates/7275/3了解更多信息

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 2018-10-25
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 2020-02-09
      • 2022-06-30
      相关资源
      最近更新 更多