뷰 인스턴스는 뷰로 화면을 개발하기 위해 필수적으로 생성해야하는 기본 단위이다.
뷰 인스턴스 생성
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>뷰 인스턴스 생성</title>
</head>
<body>
<div id='app'>
{{message}}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
}
});
</script>
</body>
</html>
new Vue()로 인스턴스를 생성할 때 Vue를 생성자라고 한다. Vue 생성자는 뷰 라이브러리를 로딩하고 나면 접근 가능하다. 생성자를 사용하는 이유는 뷰로 개발할 때 필요한 기능들을 생성자에 미리 정의해 놓고 사용자가 그 기능을 재정의하여 편리하게 사용하도록 하기 위함이다.
뷰 인스턴스 옵션 속성
뷰 인스턴스 옵션 속성은 인스턴스를 생성할 때 재정의할 data, el, template등의 속성을 의미한다.
예를 들어 위의 예제에서는 data라는 미리 정의되어 있는 속성을 사용했다.
그 안에 message라는 새로운 속성을 추가하고 값을 주었다.
el속성은 뷰로 만든 화면이 그려지는 시작점을 의미한다. 뷰 인스턴스로 화면을 렌더링할 때 화면이 그려질 위치의 돔 요소를 지정해 주어야한다.
인스턴스 생성
1. beforeCreate
2. created
3. beforeMount
4. mounted
5. beforeUpdate
6. updated
7. beforeDestroy
8. destroyed
라이플사이클 실습예제
<html>
<head>
<title>Vue Instance Lifecycle</title>
</head>
<body>
<div id="app">
{{ message }}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
},
beforeCreate: function() {
console.log("beforeCreate");
},
created: function() {
console.log("created");
},
mounted: function() {
console.log("mounted");
this.message = 'Hello Vue!';
},
updated: function() {
console.log("updated");
}
});
</script>
</body>
</html>