我正在尝试找到一种方法来动态更改哪个_variables.scss
文件根据我的Nuxt.js通用Web应用程序中的Vuex存储中的已保存状态进行全局加载。在nuxt.config.js
文件之外有没有可能的方法呢?
我无法与公司政策分享大部分代码,但让我设置我所在的位置。我们有不同类型的客户试图访问我们的网络应用程序版本。每种类型都登录不同的域,即绿色客户通过www.green.com/login
登录,红色客户通过www.red.com/login
登录,等等。布局的主题,意思是颜色,字体等,由_variables.scss
加载确定。
目前我在我的Nuxt.js应用程序中有中间件theme.js
获取域,分割主机(www.red.com
变为red
)并作为state.theme
保存到vuex商店。
现在我无法弄清楚如何根据状态动态加载red_variables.scss
或green_variables.scss
。
经过一些试验和错误后发现了一个解决方案,但并不优雅,但它确实有效。创建了一个名为theme.js
的中间件文件,它看起来像这样:
const domain = host.split(':')[0]
switch (true) {
case domain.includes('red.com'):
return {
theme: 'red'
}
case domain.includes('green.com'):
return {
theme: 'green'
}
/*** more cases for different themes ***/
default:
return 'main'
}
}
function loadTheme(theme) {
import('~assets/css/' + theme + '.scss')
}
export default function({ app, req, store, error }) {
let theme = store.state.theme
if (!theme && process.server) {
if (req && req.headers && req.headers.host) {
const themeSettings = mapHostToTheme(req.headers.host)
theme = themeSettings.theme
store.commit('setTheme', theme)
}
}
if (!theme) {
return error({
statusCode: 500,
message: 'Unable to determine host'
})
}
loadTheme(theme)
}
基本上抓取主机名,确认域,将主题名称添加到商店,然后根据存储在Vuex状态的名称加载正确的.scss
文件。