본문 바로가기
카테고리 없음

vue3 한개의 스크립트로 여러페이지에서 사용하기

by uni:D 2024. 6. 28.

 

 

`<script setup>`은 Vue 3.2부터 도입된 문법으로, 컴포넌트의 setup 함수를 더 간결하게 작성할 수 있습니다. 아래는 `useAlert` Composition 함수를 `<script setup>` 상단에 사용하는 방법입니다.

### 1. `useAlert` Composition 함수 정의

먼저, `useAlert` Composition 함수를 정의합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { ref } from 'vue'
 
export function useAlert() {
  const showAlert = ref(false)
 
  const vAlert = () => {
    showAlert.value = true
    setTimeout(() => {
      showAlert.value = false
    }, 2000)
  }
 
  return {
    showAlert,
    vAlert
  }
}
 
cs

 

 

### 2. `useAlert`을 사용하는 컴포넌트 정의
이제 `<script setup>`을 사용하는 컴포넌트에서 `useAlert`을 사용합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
  <div>
    <button @click="vAlert">Show Alert</button>
    <div v-if="showAlert" class="alert">
      Alert is shown!
    </div>
  </div>
</template>
 
<script setup>
import { useAlert } from '../composables/useAlert'
 
const { showAlert, vAlert } = useAlert()
</script>
cs

 

### 3. 다른 컴포넌트에서도 동일하게 사용
다른 컴포넌트에서도 `<script setup>`을 사용하여 `useAlert`을 적용할 수 있습니다.

### 전체 프로젝트 구조
- `src/`
  - `composables/`
    - `useAlert.js`
  - `components/`
    - `AlertComponent.vue`
    - `AnotherComponent.vue`

 

### 결론
이렇게 하면 `<script setup>` 상단에 `useAlert`을 불러와 사용할 수 있습니다. Vue 3.2 이상의 버전을 사용하고 있으며, `<script setup>` 구문을 활용하여 Composition API를 간편하게 적용할 수 있습니다. 이 방법으로 여러 컴포넌트에서 동일한 알림 로직을 쉽게 재사용할 수 있습니다.