vue에서는 component를 글로벌 컴포넌트로 등록할 수도 있고, 로컬 컴포넌트로도 등록할 수 있다.
글로벌 컴포넌트로 등록하면 모든 파일에서 컴포넌트를 사용할 수 있고, 로컬 컴포넌트로 등록하면 컴포넌트를 등록한 파일에서만 해당 컴포넌트를 사용할 수 있다.
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");
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
라고 넘겨주어도 알아서 변형해서 잘 사용하기 때문에 위와 같이 써도 문제 없다.