์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋ฅผ ํ™œ์„ฑํ™” ํ•ด์ฃผ์„ธ์š”

Vue 3 Global Properties and Typescript

 ·   ·  โ˜• 1 min read  ·  โœ๏ธ Yogo

๊ธฐ์กด v2์—์„œ๋Š” prototype์— ๋ณ€์ˆ˜๋‚˜ ๋ชจ๋“ˆ์„ ์ •์˜ํ•˜๋ฉด this ํ‚ค์›Œ๋“œ๋ฅผ ์ด์šฉํ•˜์—ฌ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ์—ˆ๋Š”๋ฐ v3 ๋ถ€ํ„ฐ๋Š” config์˜ globalProperties์— ์ •์˜๋ฅผ ํ•˜๋„๋ก ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

1
2
3
4
5
6
// Before
Vue.prototype.$http = () => {}

// After
const app = Vue.createApp({})
app.config.globalProperties.$http = () => {}

Typescript๋ฅผ ์“ฐ๋Š” ๊ฒฝ์šฐ ComponentCustomProperties ์ธํ„ฐํŽ˜์ด์Šค์— ์ •์˜ํ•˜๋Š” ๋ณ€์ˆ˜๋‚˜ ๋ชจ๋“ˆ์— ๋Œ€ํ•œ Type ์„ ์–ธ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.

๋‹จ, ๊ธฐ๋ณธ์œผ๋กœ ์„ ์–ธ๋˜๋Š” ์ผ๋ถ€ ๋ชจ๋“ˆ(e.g. $router)์— ๋Œ€ํ•œ ํƒ€์ž…๋„ ํ•จ๊ป˜ ์„ ์–ธํ•ด์•ผ ํ•˜๋Š” ๊ฒƒ์œผ๋กœ ๋ณด์ž…๋‹ˆ๋‹ค.
์ฐธ์กฐ ๋งํฌ12

1
2
3
4
5
6
declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $http: Function;
    $router: Router;
  }
}