Home > Back-end >  NuxtJS how to transfer colors from store json to css vars?
NuxtJS how to transfer colors from store json to css vars?

Time:03-13

Im fetching colors from backend from vuex store, and i need to set that colors to css variables. And this variables need to be aviable on every page. how i can do that?

CodePudding user response:

Assume you load the color settings on nuxtServerInit action in Vuex (ref), and the format is:

{
  primary: '#F00',
  secondary: '#000'
}

By layouts

You can bind those variables as inline styles (ref) to the root element of your layout (ref), for example, layouts/default.vue:

<template>
  <div :style="styles">
    <nuxt />
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  computed: {
    ...mapState([
      'colorsFromBackend'
    ]),
    styles () {
      const obj = {}
      for (const key in this.colorsFromBackend) {
        obj[`--${key}`] = this.colorsFromBackend[key]
      }
      return obj
    }
  }
}
</script>

Then you can use the variables under the layout:

<template>
  <div >CSS Variable Testing</div>
</template>

<style scoped>
.demo {
  color: var(--primary);
  background: var(--secondary);
}
</style>

Here is a live demo: https://codesandbox.io/s/css-variable-with-nuxt-js-7lp9t4


By plugins

Alternatively, if you want to use the variables globally, you can done this by inserting a style tag to <head> through a Nuxt plugin (ref), the plugin will be executed in client only before rendering Vue components (ref).

First, add the plugin configuration in nuxt.config.js:

export default {
  // ...
  plugins: [
    {
      src: '~/plugins/css-var.js',
      mode: 'client' // Important for running in client side only
    }
  ]
}

Then, add the plugin file css-var.js under plugins/ directory:

export default ({ app, store }) => {
  // Fetch the color object from Vuex
  const colorsFromBackend = store.state.colorsFromBackend
  // Set the css content
  let styleContent = ''
  for (const key in colorsFromBackend) {
    styleContent  = `--${key}: ${colorsFromBackend[key]};`
  }

  // Create a style tag
  const style = document.createElement('style')
  style.id = 'css-var'
  style.innerText = `:root{${styleContent}}`
  // Append the tag to the end of `head`
  document.head.appendChild(style)
}

With this approach, the css variables will be declared within :root, which points to <html> (ref), so you can access the css variables everywhere in the app.

Live demo: https://codesandbox.io/s/css-variable-with-nuxt-js-plugin-enjkri

  • Related