# Vue 實例
[](https://vuefe.cn/guide/instance.html#構造器)
## [](https://vuefe.cn/guide/instance.html#構造器)[](https://vuefe.cn/guide/instance.html#構造器 "構造器")構造器
每個 Vue.js 應用都是通過構造函數?`Vue`?創建一個?Vue 的根實例?啟動的:
~~~
var vm = new Vue({
// 選項
})
~~~
雖然沒有完全遵循?[MVVM 模式](https://en.wikipedia.org/wiki/Model_View_ViewModel), Vue 的設計無疑受到了它的啟發。因此在文檔中經常會使用?`vm`?這個變量名表示 Vue 實例。
在實例化 Vue 時,需要傳入一個選項對象,它可以包含數據、模板、掛載元素、方法、生命周期鉤子等選項。全部的選項可以在?[API 文檔](https://vuefe.cn/api)中查看。
可以擴展?`Vue`?構造器,從而用預定義選項創建可復用的組件構造器:
~~~
var MyComponent = Vue.extend({
// 擴展選項
})
// 所有的 `MyComponent` 實例都將以預定義的擴展選項被創建var myComponentInstance = new MyComponent()
~~~
盡管可以命令式地創建擴展實例,不過在多數情況下建議將組件構造器注冊為一個自定義元素,然后聲明式地用在模板中。我們將在后面詳細說明[組件系統](https://vuefe.cn/guide/components.html)。現在你只需知道所有的 Vue.js 組件其實都是被擴展的 Vue 實例。
[](https://vuefe.cn/guide/instance.html#屬性與方法)
## [](https://vuefe.cn/guide/instance.html#屬性與方法)[](https://vuefe.cn/guide/instance.html#屬性與方法 "屬性與方法")屬性與方法
每個 Vue 實例都會代理其?`data`?對象里所有的屬性:
~~~
var data = { a: 1 }
var vm = new Vue({
data: data
})
vm.a === data.a
// -> true
// 設置屬性也會影響到原始數據
vm.a = 2
data.a // -> 2
// ... 反之亦然
data.a = 3
vm.a // -> 3
~~~
注意只有這些被代理的屬性是響應的。如果在實例創建之后添加新的屬性到實例上,它不會觸發視圖更新。我們將在后面詳細討論響應系統。
除了 data 屬性, Vue 實例暴露了一些有用的實例屬性與方法。這些屬性與方法都有前綴?`$`,以便與代理的 data 屬性區分。例如:
~~~
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 (newVal, oldVal) {
// 這個回調將在 `vm.a` 改變后調用
})
~~~
注意,不要在實例屬性或者回調函數中(如?`vm.$watch('a', newVal => this.myMethod())`)使用[箭頭函數](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions)。因為箭頭函數綁定父上下文,所以?`this`?不會像預想的一樣是 Vue 實例,而是?`this.myMethod`?未被定義。
實例屬性和方法的完整列表中查閱?[API 參考](https://vuefe.cn/api)。
[](https://vuefe.cn/guide/instance.html#實例生命周期)
## [](https://vuefe.cn/guide/instance.html#實例生命周期)[](https://vuefe.cn/guide/instance.html#實例生命周期 "實例生命周期")實例生命周期
~~~
var vm = new Vue({
data: { a: 1 },
created: function () {
// `this` 指向 vm 實例
console.log('a is: ' + this.a)
}
})
// -> "a is: 1"
~~~
There are also other hooks which will be called at different stages of the instance’s lifecycle, for example?`mounted`,?`updated`, and?`destroyed`. All lifecycle hooks are called with their?`this`?context pointing to the Vue instance invoking it. You may have been wondering where the concept of “controllers” lives in the Vue world and the answer is: there are no controllers. Your custom logic for a component would be split among these lifecycle hooks.
也有一些其它的鉤子,在實例生命周期的不同階段調用,如?`mounted`、?`updated`?、`destroyed`?。鉤子的?`this`?指向調用它的 Vue 實例。一些用戶可能會問 Vue.js 是否有“控制器”的概念?答案是,沒有。組件的自定義邏輯可以分布在這些鉤子中。
[](https://vuefe.cn/guide/instance.html#生命周期圖示)
## [](https://vuefe.cn/guide/instance.html#生命周期圖示)[](https://vuefe.cn/guide/instance.html#生命周期圖示 "生命周期圖示")生命周期圖示
下圖說明了實例的生命周期。你不需要立馬弄明白所有的東西,不過以后它會有幫助。
