我從 vuex 商店的后端獲取顏色,我需要將該顏色設定為 css 變數。并且這個變數需要在每個頁面上都是可用的。我怎么能這樣做?
uj5u.com熱心網友回復:
假設您nuxtServerInit在 Vuex (ref)中加載 action 的顏色設定,格式為:
{
primary: '#F00',
secondary: '#000'
}
按布局
您可以將這些變數作為行內樣式(ref)系結到布局的根元素(ref),例如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>
然后就可以使用布局下的變數了:
<template>
<div class="demo">CSS Variable Testing</div>
</template>
<style scoped>
.demo {
color: var(--primary);
background: var(--secondary);
}
</style>
這是一個現場演示:https ://codesandbox.io/s/css-variable-with-nuxt-js-7lp9t4
通過插件
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/442222.html
