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/instance.md.
Tất cả được prefix $ để tách khỏi property do user định nghĩa.
var data = { a: 1 }var vm = new Vue({ el: '#example', data: data })vm.$data === data // truevm.$el === document.getElementById('example') // truevm.$watch('a', function (newVal, oldVal) { console.log(`a: ${oldVal} -> ${newVal}`)})
Mỗi instance đi qua các bước: setup data observation, compile template, mount vào DOM, update DOM khi data thay đổi, teardown khi destroy. Hooks cho phép chèn code tại từng thời điểm.
new Vue({ // --- Khởi tạo --- beforeCreate() { // Instance vừa tạo, data/events chưa setup; this.$data chưa có }, created() { // Data, computed, watch, methods đã sẵn sàng; DOM chưa mount ($el chưa có) // Dùng cho: gọi API, khởi tạo state console.log('created - a is:', this.a) }, // --- Mount vào DOM --- beforeMount() { // Template đã compile, sắp mount; hầu như không dùng }, mounted() { // Instance đã mount ($el tồn tại) // Dùng cho: thao tác DOM, init thư viện third-party console.log('mounted - el:', this.$el) }, // --- Cập nhật --- beforeUpdate() { // Data đã đổi, DOM sắp re-render; có thể đọc DOM cũ trước khi patch }, updated() { // DOM đã re-render; tránh thay đổi data ở đây để khỏi loop vô hạn }, // --- Destroy --- beforeDestroy() { // Instance sắp destroy; dùng cho: cleanup listeners, timers, subscriptions }, destroyed() { // Instance đã destroy; mọi directive và event listener đã unbind }})
// SAI — arrow function không có `this` riêngnew Vue({ created: () => { console.log(this.a) // this = undefined hoặc window }})// SAI trong $watchvm.$watch('a', newValue => this.myMethod())// ĐÚNG — dùng regular functionnew Vue({ created() { console.log(this.a) // this = Vue instance }})// ĐÚNG trong $watchvm.$watch('a', function (newValue, oldValue) { this.myMethod() // this = Vue instance})
Lý do: arrow function không có this riêng nên this bind vào scope cha (window hoặc undefined ở strict mode), gây lỗi Cannot read property of undefined.
// clientlib/js/myComponent.js(function() { var el = document.getElementById('my-app') if (!el) return // guard: element không tồn tại var vm = new Vue({ el: el, data: function() { return { // Parse JSON data từ HTL thông qua data attribute items: JSON.parse(el.dataset.items || '[]'), loading: false } }, created: function() { console.log('[MyApp] Vue instance created, items:', this.items.length) }, mounted: function() { console.log('[MyApp] Mounted to DOM element:', this.$el.id) } })})()
var vm = new Vue({ el: '#app', data: { items: [] }, methods: { loadItems: function() { this.items = fetchItems() // data thay đổi // DOM chưa cập nhật tại đây, query có thể sai console.log(this.$el.querySelectorAll('.item').length) // Đợi DOM update xong this.$nextTick(function() { console.log(this.$el.querySelectorAll('.item').length) // chính xác }) } }})