【问题标题】:Is it possible to share variable between SASS and Javascript in Vuex(Nuxt)?是否可以在 Vuex(Nuxt) 中的 SASS 和 Javascript 之间共享变量?
【发布时间】:2019-12-24 20:01:55
【问题描述】:

如题。我使用 Vue、Vuex(Nuxt),我们还使用以下方式共享所有 mixins 和 sass 变量: @nuxtjs/style-resources": "^1.0.0"

哪个是"nuxt-sass-resources-loader": "^2.0.5"的更新版本

我知道我可以使用 Webpack,例如 here 所以我的问题是 - 是否可以以类似的方式进行操作以及如何配置它?我应该安装什么以及如何将其添加到我的 nuxt.config.js?

编辑: 我还找到了that article,但对我来说它不起作用。

【问题讨论】:

  • @Aldarund 我不想模块化我的 css。有时我们使用外部库,我们需要添加一些样式作为 js 参数。这就是为什么我想与 js 共享 sass 变量。
  • 所以在 js 中使用 css vars 的方式是使用 css 模块。你链接的文章是为了反应。最终它仍然使用 css 模块
  • 我也对这个问题感兴趣。我看到的方法是挂钩 nuxt 构建并使用所有 sass 变量编写 json 文件。我目前正在尝试这样做,但缺少一种获取所有 sass 变量的方法......我正在努力使用 webpack:/
  • 我正在寻找更好的方法。我有所有的 mixins,样式在组件之间共享,我只想访问不仅在样式内部而且在组件脚本部分中的变量,所以我什至可以使用 sass 变量内联样式。所以我相信它更像是 Webpack 配置,但我不确定以及如何实现这一点。 @ManUtopiK 请添加 +1 以获得更好的 SEO

标签: sass vuejs2 vuex nuxt.js


【解决方案1】:

简短回答:是的。

SASS 提供了导出变量的选项,您可以将其作为模块导入并像任何其他对象一样使用。带有 sass-loader 和 node-sass 的 Webpack 处理导入。

例子:

// in assets/scss/variables.scss

$white-color: #fcf5ed;

// the :export directive is the magic sauce for webpack
:export {
  whitecolor: $white-color;
}

// in store.js

import Styles from '~/assets/scss/variables.scss'

export const state = () => ({
  styles: {...Styles}
})

// in component
...
computed: {
  styles() {
    return this.$store.state.styles;
  }
}

更长的答案:您也可以对所有内容都使用 css 变量。

例如

// in assets/scss/variables.scss

$white-color: #fcf5ed;

:root {
  --whitecolor: $white-color;
}

// in component
...
mounted() {
  this.$el.style.color = 'var(--whitecolor)';
}

<style>
.component {
  color: var(--whitecolor);
}
</style>

【讨论】:

    猜你喜欢
    • 2011-06-25
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多