Vue

Vue3 다크모드 적용버튼 만들기 (VueUse, TailwindCss)

뜻 지, 깨달음 오 2023. 2. 2. 15:03

참고영상)

https://www.youtube.com/watch?v=7_mqThfC_yM 

 

1. TailwindCss 설치하기

https://tailwindcss.com/docs/guides/vite#vue

 

Install Tailwind CSS with Vite - Tailwind CSS

Setting up Tailwind CSS in a Vite project.

tailwindcss.com

npm install -D tailwindcss postcss autoprefixer

 

 

2. VueUse 라이브러리를 설치한다

npm i @vueuse/core

 

 

3. 내가 다크모드를 만들고 싶은 페이지에 import 한다

import { useDark, useToggle } from "@vueuse/core";

const isDark = useDark();
const toggleDark = useToggle(isDark);

 

 

4. 데이터에 넣는다

export default {
  name: "페이지이름",
  components: {
	페이지에 필요한 컴포넌트1,
    페이지에 필요한 컴포넌트2
  },
  data() {
    return {
      isDark,
      toggleDark,
    };
  },
  methods: {
  }
}

 

 

5. 다크모드 버튼에 연결한다

    <div class="flex" @click="toggleDark()">
      <button class="settings-button">다크모드</button>
    </div>

 

 

전체 코드

<template>
    <div class="flex" @click="toggleDark()">
      <button class="settings-button">다크모드</button>
    </div>
</template>

<script>
import { useDark, useToggle } from "@vueuse/core";

const isDark = useDark();
const toggleDark = useToggle(isDark);

export default {
  name: "컴포넌트 이름",
  components: {
  },
  data() {
    return {
      isDark,
      toggleDark,
    };
  },
}
</script>

<style lang="postcss" scoped>
.logout {
  @apply fixed inset-x-0 flex flex-wrap bottom-16 border-t text-zz-light-p font-spoq text-xl pt-3
}
</style>

 

 

6. 이 페이지 말고 다른 페이지들에도 다크모드를 적용하고 싶다면, 해당 페이지에서 import 하면 된다

 

아래 예시는 내 앱뷰의 스크립트창이다.

import { useDark } from "@vueuse/core";

const isDark = useDark();
export default {
  name: 'App',
  data() {
    return {
      isDark
    }
  },
  components: {},
};