【问题标题】:Is there a way to switch the a globally defined variables scss file in Nuxt.js using Vuex and Middleware?有没有办法使用 Vuex 和中间件在 Nuxt.js 中切换全局定义的变量 scss 文件?
【发布时间】:2019-09-14 06:43:20
【问题描述】:

我正在尝试找到一种方法来动态更改哪个_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.scssgreen_variables.scss

【问题讨论】:

  • 你不应该改用css变量吗?似乎是一个完美的用例

标签: sass vuex middleware nuxt.js


【解决方案1】:

因此,经过反复试验,找到了一个解决方案,虽然并不优雅,但它确实有效。创建了一个名为 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 文件。

【讨论】:

  • 嗨!你在哪里加载了原始的_variables?
猜你喜欢
  • 2020-01-07
  • 2021-10-07
  • 1970-01-01
  • 2016-05-23
  • 2019-08-17
  • 1970-01-01
  • 2018-06-06
  • 1970-01-01
  • 2017-09-01
相关资源
最近更新 更多