简体   繁体   English

如何在带有 Nuxt.js ar 服务器端的 css 中使用 v-bind

[英]How to use v-bind in css with Nuxt.js ar Server Side

I want to have dynamic color scheme to my pages.我想在我的页面上使用动态配色方案。 Based on the url, I send an API request that fetches the color scheme from the database.基于 url,我发送了一个 API 请求,从数据库中获取配色方案。

For this, I fetch the colors in the nuxtServerInit store hook.为此,我在 nuxtServerInit 存储挂钩中获取颜色。 I then use v-bind() in CSS to dynamically color the components.然后,我在 CSS 中使用v-bind()为组件动态着色。

For reference, https://vuejs.org/api/sfc-css-features.html#css-modules .作为参考, https://vuejs.org/api/sfc-css-features.html#css-modules Ex:前任:

    #main-container {
      max-width: 500px;
      margin: auto;
      background-color: v-bind('designTemplate.backgroundColor');
    }

Here, designTemplate is a computed variable that fetches the value from the store.在这里,designTemplate 是一个计算变量,它从存储中获取值。

I am using SSG.我正在使用 SSG。 On inspection of the generated files, I can see that the colors are not bound to css and the server rendered page does not have the required colors.在检查生成的文件时,我可以看到颜色未绑定到 css,并且服务器呈现的页面没有所需的颜色。

In the generated file, I am seeing在生成的文件中,我看到

.class-name[data-v-15114cda]{background-color:var(--fec1f67e)}

But the css variable fec1f7e is not found in the file.但是在文件中找不到 css 变量 fec1f7e。 Only during hydration is the colors actually applied.只有在水合过程中才会实际应用颜色。

Update: Solved the problem.更新:解决了问题。 Used an alternate way of accomplishing my requirement.使用替代方法来完成我的要求。

Instead of using v-bind in css, I created root level css variables.我没有在 css 中使用 v-bind,而是创建了根级 css 变量。 This was done in the head section of my page.这是在我页面的头部部分完成的。

head() {
 return {
   style: [
        {
          cssText: `
            :root {
              --base-color: ${this.designTemplate.baseColor};
              --background-color: ${this.designTemplate.backgroundColor};
            }
          `,
          type: 'text/css'
        }
      ]
   }
}

With this in place, I can access these variables in all my files and style them as:有了这个,我可以在我的所有文件中访问这些变量并将它们设置为:

    #main-container {
      max-width: 500px;
      margin: auto;
      background-color: v-bind('designTemplate.backgroundColor');
    }

The css variables are injected in the head of the html and with server side generation, I get a properly colored server rendered page. css 变量被注入到 html 的头部,并且通过服务器端生成,我得到了一个正确着色的服务器渲染页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM