在 VueJS 组件中使用 sass 变量

新手上路,请多包涵

我遇到了一个需要使用变量的 VueJS 组件的相当简单的问题。问题在于让 sass 在组件内注册变量。

我尝试导入包含我的变量的 _variables.scss 文件,但没有成功。在这一点上,非常感谢任何指导,或者如果组件有另一种方式来继承样式。

我的组件.vue

 <template>
    <div class="my-color"></div>
</template>
<style lang="sass">
    .my-color {
        color: $primary-color;
    }
</style>
<script>
    export default{
        data(){
            return {}
        }
    }
</script>

Gulpfile.js

 var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');

elixir(function(mix) {
    mix.browserify('main.js');
    mix.sass('app.scss');
});

应用程序.scss

 @import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";
@import "modules/variables";

变量.scss

 $primary-color: #BA2731; //Red

原文由 Nicklas Kevin Frank 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 855
2 个回答

在每个组件中导入 _variables.scss 似乎是迄今为止我找到的唯一解决方案( 根据这个问题它应该可以工作)。

 <template>
    <div class="my-color"></div>
</template>
<style lang="sass">
    @import 'path/to/your/_variable.scss'; // Using this should get you the variables
    .my-color {
        color: $primary-color;
    }
</style>
<script>
    export default{
        data(){
            return {}
        }
    }
</script>

由于您只包含变量,因此这应该不是问题。

但正如问题中提到的,请注意:您应该只在每个组件中包含抽象实体(变量、扩展、混合),而不是具体的 CSS 规则。

原文由 nils 发布,翻译遵循 CC BY-SA 3.0 许可协议

假设你正在使用 vue-cli ,试试这个。

如果您尚未安装 sass 加载程序:

 npm install -D sass-loader node-sass

然后在 vue.config.js

 const path = require('path');

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        data: `@import "@/pathto/variables.scss";`
      }
    }
  }
};

在您的组件中:

 <style lang="sass">
    .my-color {
        color: $primary-color;
    }
</style>

资源:

编辑:

从 sass-loader 8 开始, data 需要是 prependData (感谢@ben-y 指出这一点):

 const path = require('path');

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        prependData: `@import "@/pathto/variables.scss";`
      }
    }
  }
};

原文由 logee 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题