본문 바로가기
Vue

🙎 vue에서 scss를 통해 간단하게 theme별로 관리해보기

by frontChoi 2023. 1. 24.
반응형

🙋‍♀️ vue.config.js 전역 scss 세팅

reset.scss와 색을 관리하는 _variables.scss,  프로젝트 전에 scss를 관리하는 styles.scss를 전역으로 설정한다.

const { defineConfig } = require('@vue/cli-service');
module.exports = defineConfig({
  transpileDependencies: true,
  css: {
    loaderOptions: {
      scss: {
        additionalData: `
          @import "~@/assets/styles/reset.scss";
          @import "~@/assets/styles/_variables.scss";
          @import "~@/assets/styles/styles.scss";
        `,
      },
    },
  },
});

🧏‍♂️  theme1.scss , theme2.scss 를 통해 각 테마별 색 관리

assets/styles/theme1.scss, assets/styles/theme2.scss를 만들어 각 테마별 색을 관리 할 수 있도록 한다.

//theme1.scss
$theme-1: (
  name: 'theme1',
  text-color: $purple,
  bg-color: $green,
);
//theme2.scss
$theme-2: (
  name: 'theme2',
  text-color: $red,
  bg-color: $yellow,
);

☔️ styles.scss에  theme1.scss,theme2.scss의  value 값을 가져 올 수 있는 함수 생성

@function map-get-value($map, $value) {
  @if map-has-key($map, $key) {
    @return map-get($map, $value);
  } @else {
    @error "Error : Specified key #{key} does not exist in the mapping #{map-get($map,name)}";
  }
}

🌊  mixin을 통해 해당 테마에 맞는 color를 return

여기서 map-get-value의 두번째 인자는 theme1.scss,theme2.scss에 선언되어야 하는 key이어야 한다.

@mixin set-theme($map) {
  .title {
    font-weight: 200;
    color: map-get-value($map, text-color); //map-get-value 함수를 통해 return
  }

  .layout {
    display: inline-block;
    width: 100px;
    height: 100px;
    background-color: map-get-value($map, bg-color); //여기서 bg-color는 theme1.scss 또는 theme2.scss에 선언되어야 한다.
  }
}

 

🏚 styles.scss에 include의 선언을 통해 @mixin 적용

.theme1 {
  @include set-theme($theme-1);
}

.theme2 {
  @include set-theme($theme-2);
}

 

 

🗾 최종 styles.scss 코드

@import '~@/assets/styles/theme1.scss';
@import '~@/assets/styles/theme2.scss';

// 해당 map의 key에 맞는 value를 return
@function map-get-value($map, $key) {
  @if map-has-key($map, $key) {
    @return map-get($map, $key);
  } @else {
    @error "Error : Specified key #{key} does not exist in the mapping #{map-get($map,name)}";
  }
}

//mixin을 통해 해당 테마에 맞는 color를 return
@mixin set-theme($map) {
  .title {
    font-weight: 200;
    color: map-get-value($map, text-color); //map-get-value 함수를 통해 return
  }

  .layout {
    display: inline-block;
    width: 100px;
    height: 100px;
    background-color: map-get-value($map, bg-color); //여기서 bg-color는 theme1.scss 또는 theme2.scss에 선언되어야 한다.
  }
}

//styles.scss에 include의 선언을 통해 @mixin 적용
//set theme
.theme1 {
  @include set-theme($theme-1);
}

.theme2 {
  @include set-theme($theme-2);
}

 

 

🌁  theme별 css 적용 결과

테마별 css 적용

theme1,theme2마다 title,layout 색값이 변경된 것을 알 수가 있다. 

반응형

'Vue' 카테고리의 다른 글

🖖 vue jest router 생긴 문제  (0) 2023.03.16
👊 vue jest study기록  (0) 2023.03.03
🛎 vuex 모듈화  (0) 2023.01.18
🐅 vee-validate 적용  (0) 2022.08.07
⚓ Vue Slot으로 테이블 구현  (0) 2022.05.31

댓글