02. The Vue Instance Flashcards
Vue instance
(short for ViewModel) to refer to our Vue instance
var vm = new Vue({ // options })
options object
When you create a Vue instance, you pass in an options object
https://vuejs.org/v2/api/#Options-Data
new Vue crea ….?
A Vue application consists of a root Vue instance created with new Vue, optionally organized into a tree of nested, reusable components.
Root Instance └─ TodoList ├─ TodoItem │ ├─ DeleteTodoButton │ └─ EditTodoButton └─ TodoListFooter ├─ ClearTodosButton └─ TodoListStatistics
Vue componentes are…?
all Vue components are also Vue instances, and so accept the same options object (except for a few root-specific options)
Vue’s reactivity system
When a Vue instance is created, it adds all the properties found in its data object to Vue’s reactivity system. When the values of those properties change, the view will “react”, updating to match the new values.
var data = { a: 1 }
// The object is added to a Vue instance var vm = new Vue({ data: data })
// Getting the property on the instance // returns the one from the original data vm.a == data.a // => true
// Setting the property on the instance // also affects the original data vm.a = 2 data.a // => 2
// … and vice-versa
data. a = 3
vm. a // => 3
properties in data are only reactive if they existed
When this data changes, the view will re-render. It should be noted that properties in data are only reactive if they existed when the instance was created. That means if you add a new property, like:
vm.b = ‘hi’
Then changes to b will not trigger any view updates. If you know you’ll need a property later, but it starts out empty or non-existent, you’ll need to set some initial value. For example:
data: { newTodoText: '', visitCount: 0, hideCompletedTodos: false, todos: [], error: null }
Object.freeze()
The only exception to this being the use of Object.freeze(), which prevents existing properties from being changed, which also means the reactivity system can’t track changes.
$
Vue instances expose a number of useful instance properties and methods. These are prefixed with $ to differentiate them from user-defined properties
Instance Lifecycle Hooks
Each Vue instance goes through a series of initialization steps when it’s created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes. Along the way, it also runs functions called lifecycle hooks, giving users the opportunity to add their own code at specific stages.
such as mounted, updated, and destroyed. All lifecycle hooks are called with their this context pointing to the Vue instance invoking it
Don’t use arrow functions on an options property or callback, such as created: () => console.log(this.a) or vm.$watch(‘a’, newValue => this.myMethod())