vue3 전역변수 사용하기

javascript 에는 static 이 없다. const 를 사용하여 전역변수를 사용하는데 vue3 에선 다르게 사용하여 기록을 남긴다.

  1. main.ts 수정
import {createApp} from 'vue'
import App from './App.vue'
import router from "@/router";

const app = createApp( App );

app.use( router ).mount( '#app' );

app.config.globalProperties.API_SERVER_IP = ( window.location.hostname == 'https://를제외한서버도메인' ? 'https://서버도메인' : 'http://127.0.0.1:3000' );
main.ts
app.config.globalProperties.전역변수명 = {value}

이 부분이 핵심이다. 유틸 클래스를 넣어도 되고 일반 변수를 넣어도 된다. 본인은 구동환경에 따라 api server ip 를 자동으로 변경하는 코드로 사용했다.

2. 사용

<script setup>
.
.
.

const { proxy } = getCurrentInstance();
.
.
.
get( proxy.API_SERVER_IP + '/test', ...

</script>

사용하려는 컴퍼넌트의 script 속에

const { proxy } = getCurrentInstance();

로 선언후

proxy.전역변수명

식으로 사용하면 된다.

ps. 구글링 결과 getCurrentInstance 를 사용하지 않고 바로 this.전역변수명 식으로 사용해도 된다는데 어째선지 내 코드에선 동작이 되질 않았다.

Subscribe to X세대 신입사원

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe
774-86-01972 cinnabar.3d@gmail.com