【问题标题】:How to use dynamic CSS files with Nuxt?如何在 Nuxt 中使用动态 CSS 文件?
【发布时间】:2019-07-09 03:57:49
【问题描述】:

我正在从事一个项目,该项目有不同的用户和他们的徽标。 根据 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 路径/API 调用绑定 CSS 文件,而不是把路径放在那里?

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

谢谢

【问题讨论】:

    标签: javascript css vue-router nuxt.js


    【解决方案1】:

    要动态加载 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>
    

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 酷,我可以将我所有的 css 文件放在页面中,但是如何根据客户端 API 调用/URL 调用正确的文件? =/
      猜你喜欢
      • 2022-06-30
      • 2021-08-07
      • 2020-05-30
      • 1970-01-01
      • 2021-05-19
      • 2019-03-23
      • 2020-10-13
      • 1970-01-01
      • 2013-01-24
      相关资源
      最近更新 更多