如何在 Nuxt 中使用动态 CSS 文件?

How to use dynamic CSS files with Nuxt?

我在一个项目中工作,该项目有不同的用户使用他们的徽标。 基于 API 调用,我想加载具有不同调色板的不同 CSS。

现在我在 assets 文件夹中有一个 css 文件夹,其中包含 main.js(带有我的自定义字体样式等)和另一个用于自定义调色板的文件:<color-name>-palette.css.

在我的 nuxt.config 中,我这样称呼 CSS 颜色:

  css: [
    '~/assets/style/app.styl',
    '~/assets/css/main.css',
    '~/assets/css/orange-palette.css'
  ],

有没有什么方法可以根据 URL path/API 调用来绑定 CSS 文件,而不是将路径放在那里?

我不确定我是否也可以在模板上使用它,在其中绑定 CSS 文件。可能吗?

谢谢

您可以在页面组件中使用"head"。 https://codesandbox.io/s/xr55o4yqmq

<script>
export default {
  head: {
    link: [
      {
        rel: "stylesheet",
        href: "/about.css"
      }
    ]
  }
};
</script>

要动态加载 CSS 文件,请使用 head() 而不是 head: {}。这样,值就可以是动态的。在 https://codesandbox.io/s/l4on5508zm

查看下面的代码和工作演示
<template>
  <section>
    <h1>Index</h1>
    <button @click="swap">swap</button>
    <p v-text="cur" />
  </section>
</template>

<script>
export default {
  head() {
    return {
      link: [
        {
          rel: "stylesheet",
          href: `/${this.cur}.css`
        }
      ]
    };
  },
  data() {
    return {
      cur: "light"
    };
  },
  methods: {
    swap() {
      if (this.cur === "light") {
        this.cur = "dark";
      } else {
        this.cur = "light";
      }
    }
  }
};
</script>

查看上面的代码片段,您可以引入 css 文件以通过 head() 函数在您的页面上动态使用。您可以根据用户交互(例如我的按钮点击交互)将 CSS 更改为在任何页面上即时使用。