对于需要使用变量的VueJS组件,我遇到了一个相当简单的问题。问题在于让sass在组件内注册变量。
我尝试导入包含我的变量的_variables.scss
文件,但没有运气。在这一点上,非常感谢任何指导,或者如果组件有另一种方式继承样式。
<template>
<div class="my-color"></div>
</template>
<style lang="sass">
.my-color {
color: $primary-color;
}
</style>
<script>
export default{
data(){
return {}
}
}
</script>
var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');
elixir(function(mix) {
mix.browserify('main.js');
mix.sass('app.scss');
});
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";
@import "modules/variables";
$primary-color: #BA2731; //Red
在每个组件中导入_variables.scss
似乎是我迄今为止找到的唯一解决方案(it should work, according to this issue)。
<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规则。
假设你正在使用vue-cli,试试这个。
如果您还没有安装sass loader:
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>
资源:
对于我的项目,我使用了Vue CLI webpack,这是一个适合我的解决方案。
我在App.vue
文件中管理我的所有SCSS。在我的每个Component.vue
我停止使用<style></style>
并开始创建一个单独的component.scss
。
所以我的src
文件夹看起来像:
/src
/assets
/components
/compA
CompA.vue
compA.scss
/compB
CompB.vue
compB.scss
App.vue
main.js
而我的App.vue
看起来像
<template> ... </template>
<script> ... </script>
<style lang="less">
//Bootstrap
@import "../node_modules/bootstrap-sass/assets/stylesheets/bootstrap";
//Components
@import "components/compA.scss";
@import "components/compB.scss";
</style>
这种设置的优点是可以在一个位置管理所有样式,并且还能够使用所有引导变量和mixin。
我走了这条路,因为当我在所有组件中导入Boostrap SCSS时,我的应用程序的大小不断增长。如果我只导入变量,那么增加可以忽略不计,但是当我导入整个Boostrap SCSS时,增加变得很大。我这样做,所以我可以使用mixins并扩展一些现有的样式。