Vue 컴포넌트 전역등록

김병훈·2021년 8월 11일
0

Vue

목록 보기
2/2

누구에게 필요한 내용일까?

  • 중복으로 사용되는 컴포넌트가 있는데, 매번 등록해줘야 할까? 싶은 사람

참고

예시

컴포넌트 구조

- main.js
- App.vue

  /components
    - Form1
    - Form2
    - Form3
    
    /Common
      - TextInput
      - SelectInput

Form1, Form2, Form3. 3개의 컴포넌트에서 TextInputSelectInput을 사용하고 있다.
컴포넌트마다 사용하는 TextInputSelectInputimport해도 되지만,
전역 컴포넌트로 선언하여, 쉽게 불러오고 싶다.

코드

// main.js
import { createApp } from "vue"
import App from "./App.vue"
// 전역으로 등록할 컴포넌트를 import 합니다.
import TextInput from "./components/Common/TextInput.vue"
import SelectInput from "./components/Common/SelectInput.vue"

const app = createApp(App)
// 컴포넌트를 등록합니다.
// app.component(사용할 시 호출할 이름, 등록할 컴포넌트)
app.component("TextInput", TextInput)
app.component("SelectInput", SelectInput)

app.mount("#app")

전역에서 사용할 컴포넌트를 main.js에 등록합니다.

<!-- Form1.vue -->
<template>
  <form>
    <TextInput />
    <TextInput />
    <SelectInput />
  </form>
</template>
<script>
  // import TextInput from "./Common/TextInput.vue"
  // import SelectInput from "./Common/SelectInput.vue"
  
  export default {
    // components: { TextInput, SelectInput }
  }
</script>

전역으로 등록한 컴포넌트는 별도로 import 하지 않더라도 사용이 가능합니다.

profile
재밌는 걸 만드는 것을 좋아하는 메이커

0개의 댓글