Vue instance
Directory
Create a Vue instance
Every Vue application starts by creating a new Vue instance using the Vue
function:
var vm = new Vue({ // 选项 })
Although it does not fully follow the MVVM model, Vue's The design was also inspired by it. Therefore, the variable name vm (abbreviation of ViewModel) is often used in documents to represent Vue instances.
When creating a Vue instance, you can pass in an options object. This tutorial describes how to use these options to create the behavior you want. For reference, you can also browse the full list of options in the API documentation.
A Vue application consists of a root Vue instance
created through new Vue, and an optional nested, reusable component tree. For example, the component tree of a todo application can look like this:
根实例 └─ TodoList ├─ TodoItem │ ├─ DeleteTodoButton │ └─ EditTodoButton └─ TodoListFooter ├─ ClearTodosButton └─ TodoListStatistics
We will expand on this in detail in the Component System chapter later. But for now, you just need to understand that all Vue components are Vue instances and accept the same options object (except for some root instance-specific options).
Data and Methods
When a Vue instance is created, it data
All properties in the object are added to Vue's responsive system. When the values of these properties change, the view will "response" by matching the new values.
// 我们的数据对象 var data = { a: 1 } // 该对象被加入到一个 Vue 实例中 var vm = new Vue({ data: data }) // 获得这个实例上的属性 // 返回源数据中对应的字段 vm.a == data.a // => true // 设置属性也会影响到原始数据 vm.a = 2 data.a // => 2 // ……反之亦然 data.a = 3 vm.a // => 3
When these data change, the view will be re-rendered. It is worth noting that only properties that already exist in data
when the instance is created are reactive. That is to say, if you add a new attribute, such as:
vm.b = 'hi'
, then the change to b
will not trigger any view update. If you know you'll need a property later, but it's empty or doesn't exist initially, then you only need to set some initial value. For example:
data: { newTodoText: '', visitCount: 0, hideCompletedTodos: false, todos: [], error: null }
The only exception here is using Object.freeze()
, which prevents modification of existing properties and means that the response system can no longer track changes.
var obj = { foo: 'bar' } Object.freeze(obj) new Vue({ el: '#app', data: obj })
<div id="app"> <p>{{ foo }}</p> <!-- 这里的 `foo` 不会更新! --> <button v-on:click="foo = 'baz'">Change it</button> </div>
In addition to data properties, Vue instances also expose some useful instance properties and methods. They are prefixed with $
to distinguish them from user-defined properties. For example:
var data = { a: 1 } var vm = new Vue({ el: '#example', data: data }) vm.$data === data // => true vm.$el === document.getElementById('example') // => true // $watch 是一个实例方法 vm.$watch('a', function (newValue, oldValue) { // 这个回调将在 `vm.a` 改变后调用 })
You can check the complete list of instance properties and methods in API Reference in the future.
Instance life cycle hook
Each Vue instance needs to be After a series of initialization processes - for example, you need to set up data monitoring, compile templates, mount the instance to the DOM, and update the DOM when the data changes, etc. At the same time, some functions called life cycle hooks will also be run during this process, which gives users the opportunity to add their own code at different stages.
For example, created
Hooks can be used to execute code after an instance is created:
new Vue({ data: { a: 1 }, created: function () { // `this` 指向 vm 实例 console.log('a is: ' + this.a) } }) // => "a is: 1"
There are also some other hooks, in Different stages of the instance life cycle are called, such as mounted
, updated
, and destroyed
. The this
context of a lifecycle hook points to the Vue instance that calls it.
Do not use arrow functions on option properties or callbacks, such as
created: () => console.log(this.a)
orvm.$watch('a', newValue => this.myMethod())
. Because the arrow function does not havethis
,this
will be searched as a variable in the upper lexical scope until it is found, which often leads toUncaught TypeError: Cannot read property of undefined
orUncaught TypeError: this.myMethod is not a function
and other errors.
Life cycle diagram
The following figure shows the life of the instance cycle. You don't need to understand everything right away, but as you continue to learn and use it, its reference value will become higher and higher.