-
[Vue2] Vue 싱글 파일 컴포넌트 (Single File Component)Vue 2023. 5. 9. 23:27반응형
싱글 파일 컴포넌트(Single File Component)란?
화면의 특정 영역에 대한 HTML, CSS, JS 코드를 한 파일에서 관리하는 방법입니다.
뷰 CLI로 프로젝트를 생성하고 나면 App.vue라는 파일을 확인할 수 있습니다.
이처럼 vue 확장자를 가진 파일을 모두 싱글 파일 컴포넌트라고 합니다.
사용 방법(코드)
<!-- .vue 파일 구조 --> <template> <!-- html (뷰 컴포넌트의 표현단, 템플릿 문법) --> </template> <script> // 자바스크립트 (뷰 컴포넌트 내용) </script> <style> /* CSS (뷰 템플릿의 스타일링) */ </style>
<template>
- 컴포넌트가 렌더링될 때 화면에 보여줄 HTML 태그 부분
- 데이터 바인딩을 위한 표현식으로 {{...}} 사용
- 디렉티브(v-*)를 이용해서 데이터 바인딩, 이벤트 처리 및 동적 화면 제어
<script>
- name: 컴포넌트 이름 선언
- data: 컴포넌트 데이터 선언
- methods: 컴포넌트 이벤트 처리를 위한 메소드 선언
- beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy, destroyed: 컴포넌트 라이프사이클 훅(Lifecycle Hook) 선언
- 데이터 바인딩을 위한 선언
- watch: 데이터 및 상태 감시를 위한 선언
<style>
- <style> 태그: 전역 style
- <style scoped> 지역 style
- App.vue를 제외하고 나머지 .vue는 모두 지역 style 적용, 아니면 싱글 파일 컴포넌트 위반
ChannyBlog.vue
<template> <div> <p>{{ name }}</p><br> <button @click="updateName">Change Name</button> </div> </template> <script> export default { data() { return { name: 'Channy Blog', } }, methods: { updateName() { this.name = 'Channy blog Updated'; } } } </script> <style scoped> </style>
HomeView.vue
<template> <div> <h1>This is Home page</h1> <ChannyBlog /> </div> </template> <script> import ChannyBlog from '@/components/ChannyBlog.vue' export default { components : { ChannyBlog }, data() { return { name: "Channy", }; }, }; </script> <style scoped> h1 { color: red; } </style>
AboutView.vue
<template> <div class="about"> <h1>This is an about page</h1> <ChannyBlog /> </div> </template> <script> import ChannyBlog from '@/components/ChannyBlog.vue' export default { components : { ChannyBlog }, data() { return { name: "Channy", }; }, }; </script>
실행 화면
Home 영역
about 영역
참고 자료
https://youtu.be/t0z0kSQIr38?list=PLB7CpjPWqHOtYP7P_0Ls9XNed0NLvmkAh
2023.05.08 - [Vue] - [Vue2] Vue Router(뷰 라우터)
[Vue2] Vue Router(뷰 라우터)
Vue Router(뷰 라우터란)? 클라이언트의 요청 경로에 따라 해당하는 컴포넌트를 불러와 페이지를 구성할 수 있다. URL 변경 시 DOM을 새로 갱신하는 것이 아니라 미리 컴포넌트를 가지고 있다가 변경
valiafern-0205.tistory.com
반응형'Vue' 카테고리의 다른 글
[Vue2] vue Emit 부모 컴포넌트로 데이터 보내기 (0) 2023.05.11 [Vue2] vue 자식 컴포넌트에 데이터 보내기 (Props) (0) 2023.05.10 [Vue2] Vue Router(뷰 라우터) (0) 2023.05.08 [Vue2] Vue Cli로 뷰 설치 및 프로젝트 설치 (0) 2023.05.05 [Vue2] Vue 컴포넌트(Component) (0) 2023.05.03