[Vue.js] Global Component와 Local Component

유자·2021년 9월 25일
0

vue

목록 보기
1/3

vue에서는 component를 글로벌 컴포넌트로 등록할 수도 있고, 로컬 컴포넌트로도 등록할 수 있다.

컴포넌트 사용 범위

글로벌 컴포넌트로 등록하면 모든 파일에서 컴포넌트를 사용할 수 있고, 로컬 컴포넌트로 등록하면 컴포넌트를 등록한 파일에서만 해당 컴포넌트를 사용할 수 있다.

컴포넌트 등록 예시

(1) 글로벌 컴포넌트 등록

search-bar 컴포넌트를 글로벌 등록할 때
main.js

import { createApp } from "vue";
import App from "./App.vue";

//import 글로벌컴포넌트이름 from "글로벌컴포넌트위치";
import SearchBar from "./components/SearchBar.vue";

const app = createApp(App);

//app에 내장된 component 함수를 사용
//첫 번째 인자: html코드에서 컴포넌트를 사용할 때 쓸 태그 이름
//두 번째 인자: 글로벌 컴포넌트 이름
app.component("search-bar", SearchBar);

app.mount("#app");

(2) 로컬 컴포넌트 등록

search-bar 컴포넌트를 로컬 등록할 때
app.vue

<template>
    <search-bar></search-bar>
</template>

<script>
import SearchBar from "./components/SearchBar.vue";

export default {
  components: {	//components 속성에 로컬 컴포넌트로 등록할 컴포넌트 이름을 넣는다.
    SearchBar,	// = SearchBar: SearchBar -> 모던 자바스크립트 문법
  },
};
</script>

component 등록할 때 components 속성에 넘겨주는 객체 안에 html에서 사용할 컴포넌트 이름: 컴포넌트 이름 문법으로 넘겨주어야 하는데(ex. "search-bar": SearchBar), vue에서는 SearchBar: SearchBar라고 넘겨주어도 알아서 변형해서 잘 사용하기 때문에 위와 같이 써도 문제 없다.

profile
꾸준히 공부하기

0개의 댓글