首页 > 解决方案 > 是否可以在 Vuex(Nuxt) 中的 SASS 和 Javascript 之间共享变量?

问题描述

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

哪个是“nuxt-sass-resources-loader”的较新版本:“^2.0.5”

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

编辑:我也发现了那篇文章,但对我来说它不起作用。

标签: sassvuejs2vuexnuxt.js

解决方案


简短的回答:是的。

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>

推荐阅读