티스토리 뷰

프로그래밍

[Vue] 전역 변수 사용하기 (#2)

ReturnToHome 2025. 2. 25. 23:11

 

이번에는 공통으로 사용되는 함수들을 모아 전역 변수로 선언한 후 해당 변수를 통해 함수를 호출하는 방법을 알아보도록 하겠습니다.

먼저 공통 함수들을 선언하는 파일을 utils.js 라고 명명하고 아래와 같이 작성합니다.

 

  // utils.js
  export default {
    // 숫자 외 문자삭제 후 리턴
    inputNumber: (v) => {
        return v.replace(/[^0-9]/g, '')
    }
  }

 

그리고 main.js 에서 utils.js 파일을 import 후 전역 변수에 $utils 라는 이름으로 등록합니다.

 

  // main.js
  import { createApp } from 'vue'

  import App from './App.vue'
  import router from './router'
  import utils from './plugins/utils'

  const app = createApp(App)
  app.use(router)
  app.config.globalProperties.$utils = utils
  app.mount('#app')

 

마지막으로 화면에서는 injectgetCurrentInstance() 와 같은 선언없이 바로 $utils 를 사용하여 함수를 호출 및 사용 할 수 있습니다.

아래의 예제에서 생년월일을 입력하는 input box 에는 숫자 외 입력 시 노출되지 않으며 6자 이상 입력되지 않습니다

 

  // template.vue
  <template>
    <div>
        <div>
            <label for="birth" class="label">생년월일(6자리)</label>
            <input type="text" name="birth" id="birth" v-model="birthDay"/>
        </div>        
    </div>
  </template>

  <script setup>
    import {ref, watch} from 'vue'

    const birthDay = ref('')

    watch(() => birthDay.value, newValue => {
        nextTick(() => {
            if (newValue.length > 6) {
                birthDay.value = birthDay.value.slice(0, 6)
            } else {
                birthDay.value = $utils.inputNumber(newValue)
            }
        })
    })
  </script>

 

댓글