For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt, and this page is available as Markdown at https://nhanbe.id.vn/frontend/vue2.7/component-in-depth/vue-instance.md.

Vue Instance - developer documentation and reference notes for Vue Instance.

Vue Instance

Recovered from a request errorRecovered from a request errorĐược, mình sẽ đi sâu từng phần một về Vue Instance trong Vue 2.7. Mình chia thành các mục để bạn dễ theo dõi.


1. Vue Instance là gì?

Trong Vue 2, mọi ứng dụng Vue đều bắt đầu bằng việc tạo một root instance thông qua hàm khởi tạo new Vue():

const vm = new Vue({
  data: { message: 'Hello' }
})

vm (ViewModel) chính là Vue Instance. Nó đóng vai trò là cầu nối giữa DOM và data. Khi data thay đổi, instance tự động cập nhật DOM và ngược lại.


2. Cấu trúc một Vue Instance

Khi bạn truyền một options object vào new Vue({...}), Vue sẽ:

  1. Khởi tạo event lifecycle
  2. Thiết lập reactivity system (để theo dõi data)
  3. Biên dịch template thành render function (nếu có template)
  4. Mount vào DOM
  5. Patches DOM mỗi khi data thay đổi

3. Các thuộc tính và phương thức cốt lõi trên instance

Mỗi Vue instance đều có các thuộc tính bắt đầu bằng $:

Data & DOM

Thuộc tínhÝ nghĩaVí dụ
$dataObject reactive datathis.$data.message = 'Hi'
$propsProps nhận từ parentthis.$props.title
$elElement DOM thực mà instance đã mountthis.$el.querySelector('.btn')
$refsTruy cập component/element có refthis.$refs.input.focus()
$optionsObject options gốc dùng để tạo instancethis.$options.name

Methods

Phương thứcCông dụng
$mount(el)Gắn instance vào một DOM node
$destroy()Hủy instance, gỡ watcher, event listener
$forceUpdate()Ép re-render (ít khi dùng)
$nextTick(cb)Chạy callback sau khi DOM cập nhật xong

Event (chỉ trong component con)

Phương thứcCông dụng
$on(event, fn)Lắng nghe event
$once(event, fn)Lắng nghe 1 lần
$off(event, fn)Bỏ lắng nghe
$emit(event, payload)Phát event lên parent

4. Lifecycle Hooks — Instance sống như thế nào?

Lifecycle hook là các function được Vue gọi tự động tại các giai đoạn khác nhau của instance.

Chi tiết từng hook trong instance

HookData có reactive chưa?DOM có sẵn chưa?Dùng để làm gì?
beforeCreate❌ Chưa❌ ChưaKhông nên đụng tới data/DOM
created✅ Rồi❌ ChưaGọi API, khởi tạo logic
beforeMount✅ Rồi❌ ChưaCuối cùng sửa data trước render
mounted✅ Rồi✅ RồiTruy cập DOM, init library (Swiper, Chart...)
beforeUpdate✅ RồiDOM cũ đang hiển thịXử lý trước khi re-render
updated✅ RồiDOM mới đã hiển thịDOM manipulate sau update
beforeDestroy✅ RồiDOM cònCleanup: timer, interval, event listener
destroyed❌ Mất reactive❌ DOM đã gỡDọn dẹp cuối cùng

5. Reactivity System — "Ma thuật" bên trong Instance

Đây là phần quan trọng nhất để hiểu Vue Instance hoạt động như thế nào.

Cách Vue 2 theo dõi data

data() {
  return { count: 0 }
}

Bên trong Vue 2, nó làm các bước:

  1. Walk object: Duyệt tất cả property trong data, props, computed
  2. Object.defineProperty: Định nghĩa lại getter/setter cho từng property
  3. Dep (Dependency): Mỗi property có một Dep — danh sách các Watcher đang "theo dõi" nó
  4. Watcher: Mỗi computed, template, hoặc watch function là một Watcher
┌─────────────┐         getter          ┌─────┐
│  Template   │ ───────────────────────►│ Dep │
│  (Watcher)  │◄─────────────────────────│     │
└─────────────┘         setter notify     └─────┘
                                              ▲
                                              │
                                        ┌──────────┐
                                        │  data:   │
                                        │  count   │
                                        └──────────┘

Vì sao phải dùng this.$set?

Vue 2 dùng Object.defineProperty, nên nó chỉ phát hiện được property có sẵn khi khởi tạo. Nếu bạn thêm property mới sau đó, nó không reactive:

// ❌ Không reactive — Vue không biết để theo dõi
this.user.age = 30;

// ✅ Đúng — Vue kích hoạt reactivity cho property mới
this.$set(this.user, 'age', 30);

Với array cũng vậy — chỉ các method được wrap (push, pop, splice...) mới trigger update. Gán index trực tiếp không được:

// ❌ Sai
this.items[0] = 'new';

// ✅ Đúng
this.$set(this.items, 0, 'new');
// hoặc
this.items.splice(0, 1, 'new');

6. Root Instance vs Component Instance

Root Instance

// main.js
new Vue({
  render: h => h(App)
}).$mount('#app')
  • Không có parent — không nhận props
  • $parent === undefined
  • $root === chính nó

Component Instance (do export default { ... } tạo ra)

Mỗi khi Vue compiler gặp một component tag trong template, nó tạo một Vue component instance mới:

<!-- App.vue -->
<template>
  <HelloWorld msg="hi" />
</template>
  • Có parent: this.$parent trỏ tới App
  • Có props: this.$props.msg === 'hi'
  • Có slots: this.$slots
  • Có scoped slots: this.$scopedSlots

Ví dụ về component tree instance

Trong tree này:

  • E.$root = A
  • E.$parent = D
  • D.$children[0] = E (một trong các NavItem)

7. Render Function và Virtual DOM

Mọi Vue instance đều có một render function. Nếu bạn viết template, Vue compile thành render function.

// Template:
// <div>{{ message }}</div>

// Compile thành:
render(h) {
  return h('div', {}, [ this.message ])
}

h (createElement)

h('div',       // tag
  { class: 'box', on: { click: this.handleClick } },  // data object
  [ h('span', 'Hello') ]  // children
)

Virtual DOM là cây object JavaScript thể hiện cấu trúc DOM thực. Khi data thay đổi:

  1. Vue chạy render function → tạo new Virtual DOM tree
  2. So sánh với old Virtual DOM tree (diffing)
  3. Tính toán những node thực sự thay đổi
  4. Cập nhật DOM thật (patch) — chỉ những chỗ cần thiết

8. Instance Methods thực tế hay dùng

$watch — Theo dõi data thủ công

created() {
  const unwatch = this.$watch('count', (newVal, oldVal) => {
    console.log('count changed:', oldVal, '->', newVal);
  });
  
  // Sau này có thể bỏ theo dõi
  unwatch();
}

$refs — Truy cập DOM/Component

<template>
  <input ref="inputRef" />
  <ChildComp ref="childRef" />
</template>

<script>
export default {
  mounted() {
    // Truy cập DOM element
    this.$refs.inputRef.focus();
    
    // Truy cập component instance (gọi method của nó)
    this.$refs.childRef.someMethod();
  }
}
</script>

$nextTick — Đợi DOM cập nhật xong

methods: {
  increment() {
    this.count++;
    // DOM chưa cập nhật ngay lập tức đâu!
    console.log(this.$el.textContent); // vẫn là giá trị cũ
    
    this.$nextTick(() => {
      console.log(this.$el.textContent); // giá trị mới
    });
  }
}

9. Tổng kết

Khái niệmHiểu ngắn gọn
Vue InstanceObject JavaScript kết nối data, template, và DOM
Options object{ data, props, methods, computed, watch, lifecycle... }
ReactivityObject.defineProperty + Dep + Watcher
$set / $deleteCông cụ xử lý limit của Vue 2 reactivity
LifecycleCác giai đoạn từ khởi tạo → mount → update → destroy
Render functionh() tạo Virtual DOM tree

Bạn muốn mình đi sâu thêm phần nào? Ví dụ:

  • Reactive system code nội bộ Vue 2 (Observer, Dep, Watcher)?
  • Cách computed cache hoạt động bên trong instance?
  • Slot mechanism và scoped slots?