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.
For this, I fetch the colors in the nuxtServerInit store hook. I then use v-bind()
in CSS to dynamically color the components.
For reference, 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.
I am using 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.
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. 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. 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.