-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathindex.md
2712 lines (1835 loc) Β· 82.5 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: API
type: api
---
## Global Config
`Vue.config` is an object containing Vue's global configurations. You can modify its properties listed below before bootstrapping your application:
### silent
- **Type:** `boolean`
- **Default:** `false`
- **Usage:**
``` js
Vue.config.silent = true
```
Suppress all Vue logs and warnings.
### optionMergeStrategies
- **Type:** `{ [key: string]: Function }`
- **Default:** `{}`
- **Usage:**
``` js
Vue.config.optionMergeStrategies._my_option = function (parent, child, vm) {
return child + 1
}
const Profile = Vue.extend({
_my_option: 1
})
// Profile.options._my_option = 2
```
Define custom merging strategies for options.
The merge strategy receives the value of that option defined on the parent and child instances as the first and second arguments, respectively. The context Vue instance is passed as the third argument.
- **See also:** [Custom Option Merging Strategies](../guide/mixins.html#Custom-Option-Merge-Strategies)
### devtools
- **Type:** `boolean`
- **Default:** `true` (`false` in production builds)
- **Usage:**
``` js
// make sure to set this synchronously immediately after loading Vue
Vue.config.devtools = true
```
Configure whether to allow [vue-devtools](https://github.com/vuejs/vue-devtools) inspection. This option's default value is `true` in development builds and `false` in production builds. You can set it to `true` to enable inspection for production builds.
### errorHandler
- **Type:** `Function`
- **Default:** `undefined`
- **Usage:**
``` js
Vue.config.errorHandler = function (err, vm, info) {
// handle error
// `info` is a Vue-specific error info, e.g. which lifecycle hook
// the error was found in. Only available in 2.2.0+
}
```
Assign a handler for uncaught errors during component render function and watchers. The handler gets called with the error and the Vue instance.
> In 2.2.0+, this hook also captures errors in component lifecycle hooks. Also, when this hook is `undefined`, captured errors will be logged with `console.error` instead of crashing the app.
> In 2.4.0+, this hook also captures errors thrown inside Vue custom event handlers.
> In 2.6.0+, this hook also captures errors thrown inside `v-on` DOM listeners. In addition, if any of the covered hooks or handlers returns a Promise chain (e.g. async functions), the error from that Promise chain will also be handled.
> Error tracking services [Sentry](https://sentry.io/for/vue/) and [Bugsnag](https://docs.bugsnag.com/platforms/browsers/vue/) provide official integrations using this option.
### warnHandler
> New in 2.4.0+
- **Type:** `Function`
- **Default:** `undefined`
- **Usage:**
``` js
Vue.config.warnHandler = function (msg, vm, trace) {
// `trace` is the component hierarchy trace
}
```
Assign a custom handler for runtime Vue warnings. Note this only works during development and is ignored in production.
### ignoredElements
- **Type:** `Array<string | RegExp>`
- **Default:** `[]`
- **Usage:**
``` js
Vue.config.ignoredElements = [
'my-custom-web-component',
'another-web-component',
// Use a `RegExp` to ignore all elements that start with "ion-"
// 2.5+ only
/^ion-/
]
```
Make Vue ignore custom elements defined outside of Vue (e.g., using the Web Components APIs). Otherwise, it will throw a warning about an `Unknown custom element`, assuming that you forgot to register a global component or misspelled a component name.
### keyCodes
- **Type:** `{ [key: string]: number | Array<number> }`
- **Default:** `{}`
- **Usage:**
``` js
Vue.config.keyCodes = {
v: 86,
f1: 112,
// camelCase won`t work
mediaPlayPause: 179,
// instead you can use kebab-case with double quotation marks
"media-play-pause": 179,
up: [38, 87]
}
```
```html
<input type="text" @keyup.media-play-pause="method">
```
Define custom key alias(es) for `v-on`.
### performance
> New in 2.2.0+
- **Type:** `boolean`
- **Default:** `false (from 2.2.3+)`
- **Usage**:
Set this to `true` to enable component init, compile, render and patch performance tracing in the browser devtool performance/timeline panel. Only works in development mode and in browsers that support the [performance.mark](https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark) API.
### productionTip
> New in 2.2.0+
- **Type:** `boolean`
- **Default:** `true`
- **Usage**:
Set this to `false` to prevent the production tip on Vue startup.
## Global API
### Vue.extend( options )
- **Arguments:**
- `{Object} options`
- **Usage:**
Create a "subclass" of the base Vue constructor. The argument should be an object containing component options.
The special case to note here is the `data` option - it must be a function when used with `Vue.extend()`.
``` html
<div id="mount-point"></div>
```
``` js
// create constructor
var Profile = Vue.extend({
template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
data: function () {
return {
firstName: 'Walter',
lastName: 'White',
alias: 'Heisenberg'
}
}
})
// create an instance of Profile and mount it on an element
new Profile().$mount('#mount-point')
```
Will result in:
``` html
<p>Walter White aka Heisenberg</p>
```
- **See also:** [Components](../guide/components.html)
### Vue.nextTick( [callback, context] )
- **Arguments:**
- `{Function} [callback]`
- `{Object} [context]`
- **Usage:**
Defer the callback to be executed after the next DOM update cycle. Use it immediately after you've changed some data to wait for the DOM update.
``` js
// modify data
vm.msg = 'Hello'
// DOM not updated yet
Vue.nextTick(function () {
// DOM updated
})
// usage as a promise (2.1.0+, see note below)
Vue.nextTick()
.then(function () {
// DOM updated
})
```
> New in 2.1.0+: returns a Promise if no callback is provided and Promise is supported in the execution environment. Please note that Vue does not come with a Promise polyfill, so if you target browsers that don't support Promises natively (looking at you, IE), you will have to provide a polyfill yourself.
- **See also:** [Async Update Queue](../guide/reactivity.html#Async-Update-Queue)
### Vue.set( target, propertyName/index, value )
- **Arguments:**
- `{Object | Array} target`
- `{string | number} propertyName/index`
- `{any} value`
- **Returns:** the set value.
- **Usage:**
Adds a property to a reactive object, ensuring the new property is also reactive, so triggers view updates. This must be used to add new properties to reactive objects, as Vue cannot detect normal property additions (e.g. `this.myObject.newProperty = 'hi'`).
<p class="tip">The target object cannot be a Vue instance, or the root data object of a Vue instance.</p>
- **See also:** [Reactivity in Depth](../guide/reactivity.html)
### Vue.delete( target, propertyName/index )
- **Arguments:**
- `{Object | Array} target`
- `{string | number} propertyName/index`
> Only in 2.2.0+: Also works with Array + index.
- **Usage:**
Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.
<p class="tip">The target object cannot be a Vue instance, or the root data object of a Vue instance.</p>
- **See also:** [Reactivity in Depth](../guide/reactivity.html)
### Vue.directive( id, [definition] )
- **Arguments:**
- `{string} id`
- `{Function | Object} [definition]`
- **Usage:**
Register or retrieve a global directive.
``` js
// register
Vue.directive('my-directive', {
bind: function () {},
inserted: function () {},
update: function () {},
componentUpdated: function () {},
unbind: function () {}
})
// register (function directive)
Vue.directive('my-directive', function () {
// this will be called as `bind` and `update`
})
// getter, return the directive definition if registered
var myDirective = Vue.directive('my-directive')
```
- **See also:** [Custom Directives](../guide/custom-directive.html)
### Vue.filter( id, [definition] )
- **Arguments:**
- `{string} id`
- `{Function} [definition]`
- **Usage:**
Register or retrieve a global filter.
``` js
// register
Vue.filter('my-filter', function (value) {
// return processed value
})
// getter, return the filter if registered
var myFilter = Vue.filter('my-filter')
```
- **See also:** [Filters](../guide/filters.html)
### Vue.component( id, [definition] )
- **Arguments:**
- `{string} id`
- `{Function | Object} [definition]`
- **Usage:**
Register or retrieve a global component. Registration also automatically sets the component's `name` with the given `id`.
``` js
// register an extended constructor
Vue.component('my-component', Vue.extend({ /* ... */ }))
// register an options object (automatically call Vue.extend)
Vue.component('my-component', { /* ... */ })
// retrieve a registered component (always return constructor)
var MyComponent = Vue.component('my-component')
```
- **See also:** [Components](../guide/components.html)
### Vue.use( plugin )
- **Arguments:**
- `{Object | Function} plugin`
- **Usage:**
Install a Vue.js plugin. If the plugin is an Object, it must expose an `install` method. If it is a function itself, it will be treated as the install method. The install method will be called with Vue as the argument.
This method has to be called before calling `new Vue()`
When this method is called on the same plugin multiple times, the plugin will be installed only once.
- **See also:** [Plugins](../guide/plugins.html)
### Vue.mixin( mixin )
- **Arguments:**
- `{Object} mixin`
- **Usage:**
Apply a mixin globally, which affects every Vue instance created afterwards. This can be used by plugin authors to inject custom behavior into components. **Not recommended in application code**.
- **See also:** [Global Mixin](../guide/mixins.html#Global-Mixin)
### Vue.compile( template )
- **Arguments:**
- `{string} template`
- **Usage:**
Compiles a template string into a render function. **Only available in the full build.**
``` js
var res = Vue.compile('<div><span>{{ msg }}</span></div>')
new Vue({
data: {
msg: 'hello'
},
render: res.render,
staticRenderFns: res.staticRenderFns
})
```
- **See also:** [Render Functions](../guide/render-function.html)
### Vue.observable( object )
> New in 2.6.0+
- **Arguments:**
- `{Object} object`
- **Usage:**
Make an object reactive. Internally, Vue uses this on the object returned by the `data` function.
The returned object can be used directly inside [render functions](../guide/render-function.html) and [computed properties](../guide/computed.html), and will trigger appropriate updates when mutated. It can also be used as a minimal, cross-component state store for simple scenarios:
``` js
const state = Vue.observable({ count: 0 })
const Demo = {
render(h) {
return h('button', {
on: { click: () => { state.count++ }}
}, `count is: ${state.count}`)
}
}
```
<p class="tip">In Vue 2.x, `Vue.observable` directly mutates the object passed to it, so that it is equivalent to the object returned, as [demonstrated here](../guide/instance.html#Data-and-Methods). In Vue 3.x, a reactive proxy will be returned instead, leaving the original object non-reactive if mutated directly. Therefore, for future compatibility, we recommend always working with the object returned by `Vue.observable`, rather than the object originally passed to it.</p>
- **See also:** [Reactivity in Depth](../guide/reactivity.html)
### Vue.version
- **Details**: Provides the installed version of Vue as a string. This is especially useful for community plugins and components, where you might use different strategies for different versions.
- **Usage**:
```js
var version = Number(Vue.version.split('.')[0])
if (version === 2) {
// Vue v2.x.x
} else if (version === 1) {
// Vue v1.x.x
} else {
// Unsupported versions of Vue
}
```
## Options / Data
### data
- **Type:** `Object | Function`
- **Restriction:** Only accepts `Function` when used in a component definition.
- **Details:**
The data object for the Vue instance. Vue will recursively convert its properties into getter/setters to make it "reactive". **The object must be plain**: native objects such as browser API objects and prototype properties are ignored. A rule of thumb is that data should just be data - it is not recommended to observe objects with their own stateful behavior.
Once observed, you can no longer add reactive properties to the root data object. It is therefore recommended to declare all root-level reactive properties upfront, before creating the instance.
After the instance is created, the original data object can be accessed as `vm.$data`. The Vue instance also proxies all the properties found on the data object, so `vm.a` will be equivalent to `vm.$data.a`.
Properties that start with `_` or `$` will **not** be proxied on the Vue instance because they may conflict with Vue's internal properties and API methods. You will have to access them as `vm.$data._property`.
When defining a **component**, `data` must be declared as a function that returns the initial data object, because there will be many instances created using the same definition. If we use a plain object for `data`, that same object will be **shared by reference** across all instances created! By providing a `data` function, every time a new instance is created we can call it to return a fresh copy of the initial data.
If required, a deep clone of the original object can be obtained by passing `vm.$data` through `JSON.parse(JSON.stringify(...))`.
- **Example:**
``` js
var data = { a: 1 }
// direct instance creation
var vm = new Vue({
data: data
})
vm.a // => 1
vm.$data === data // => true
// must use function when in Vue.extend()
var Component = Vue.extend({
data: function () {
return { a: 1 }
}
})
```
Note that if you use an arrow function with the `data` property, `this` won't be the component's instance, but you can still access the instance as the function's first argument:
```js
data: vm => ({ a: vm.myProp })
```
- **See also:** [Reactivity in Depth](../guide/reactivity.html)
### props
- **Type:** `Array<string> | Object`
- **Details:**
A list/hash of attributes that are exposed to accept data from the parent component. It has an Array-based simple syntax and an alternative Object-based syntax that allows advanced configurations such as type checking, custom validation and default values.
With Object-based syntax, you can use following options:
- `type`: can be one of the following native constructors: `String`, `Number`, `Boolean`, `Array`, `Object`, `Date`, `Function`, `Symbol`, any custom constructor function or an array of those. Will check if a prop has a given type, and will throw a warning if it doesn't. [More information](../guide/components-props.html#Prop-Types) on prop types.
- `default`: `any`
Specifies a default value for the prop. If the prop is not passed, this value will be used instead. Object or array defaults must be returned from a factory function.
- `required`: `Boolean`
Defines if the prop is required. In a non-production environment, a console warning will be thrown if this value is truthy and the prop is not passed.
- `validator`: `Function`
Custom validator function that takes the prop value as the sole argument. In a non-production environment, a console warning will be thrown if this function returns a falsy value (i.e. the validation fails). You can read more about prop validation [here](../guide/components-props.html#Prop-Validation).
- **Example:**
``` js
// simple syntax
Vue.component('props-demo-simple', {
props: ['size', 'myMessage']
})
// object syntax with validation
Vue.component('props-demo-advanced', {
props: {
// type check
height: Number,
// type check plus other validations
age: {
type: Number,
default: 0,
required: true,
validator: function (value) {
return value >= 0
}
}
}
})
```
- **See also:** [Props](../guide/components-props.html)
### propsData
- **Type:** `{ [key: string]: any }`
- **Restriction:** only respected in instance creation via `new`.
- **Details:**
Pass props to an instance during its creation. This is primarily intended to make unit testing easier.
- **Example:**
``` js
var Comp = Vue.extend({
props: ['msg'],
template: '<div>{{ msg }}</div>'
})
var vm = new Comp({
propsData: {
msg: 'hello'
}
})
```
### computed
- **Type:** `{ [key: string]: Function | { get: Function, set: Function } }`
- **Details:**
Computed properties to be mixed into the Vue instance. All getters and setters have their `this` context automatically bound to the Vue instance.
Note that if you use an arrow function with a computed property, `this` won't be the component's instance, but you can still access the instance as the function's first argument:
```js
computed: {
aDouble: vm => vm.a * 2
}
```
Computed properties are cached, and only re-computed on reactive dependency changes. Note that if a certain dependency is out of the instance's scope (i.e. not reactive), the computed property will __not__ be updated.
- **Example:**
```js
var vm = new Vue({
data: { a: 1 },
computed: {
// get only
aDouble: function () {
return this.a * 2
},
// both get and set
aPlus: {
get: function () {
return this.a + 1
},
set: function (v) {
this.a = v - 1
}
}
}
})
vm.aPlus // => 2
vm.aPlus = 3
vm.a // => 2
vm.aDouble // => 4
```
- **See also:** [Computed Properties](../guide/computed.html)
### methods
- **Type:** `{ [key: string]: Function }`
- **Details:**
Methods to be mixed into the Vue instance. You can access these methods directly on the VM instance, or use them in directive expressions. All methods will have their `this` context automatically bound to the Vue instance.
<p class="tip">Note that __you should not use an arrow function to define a method__ (e.g. `plus: () => this.a++`). The reason is arrow functions bind the parent context, so `this` will not be the Vue instance as you expect and `this.a` will be undefined.</p>
- **Example:**
```js
var vm = new Vue({
data: { a: 1 },
methods: {
plus: function () {
this.a++
}
}
})
vm.plus()
vm.a // 2
```
- **See also:** [Event Handling](../guide/events.html)
### watch
- **Type:** `{ [key: string]: string | Function | Object | Array}`
- **Details:**
An object where keys are expressions to watch and values are the corresponding callbacks. The value can also be a string of a method name, or an Object that contains additional options. The Vue instance will call `$watch()` for each entry in the object at instantiation.
- **Example:**
``` js
var vm = new Vue({
data: {
a: 1,
b: 2,
c: 3,
d: 4,
e: {
f: {
g: 5
}
}
},
watch: {
a: function (val, oldVal) {
console.log('new: %s, old: %s', val, oldVal)
},
// string method name
b: 'someMethod',
// the callback will be called whenever any of the watched object properties change regardless of their nested depth
c: {
handler: function (val, oldVal) { /* ... */ },
deep: true
},
// the callback will be called immediately after the start of the observation
d: {
handler: 'someMethod',
immediate: true
},
// you can pass array of callbacks, they will be called one-by-one
e: [
'handle1',
function handle2 (val, oldVal) { /* ... */ },
{
handler: function handle3 (val, oldVal) { /* ... */ },
/* ... */
}
],
// watch vm.e.f's value: {g: 5}
'e.f': function (val, oldVal) { /* ... */ }
}
})
vm.a = 2 // => new: 2, old: 1
```
<p class="tip">Note that __you should not use an arrow function to define a watcher__ (e.g. `searchQuery: newValue => this.updateAutocomplete(newValue)`). The reason is arrow functions bind the parent context, so `this` will not be the Vue instance as you expect and `this.updateAutocomplete` will be undefined.</p>
- **See also:** [Instance Methods / Data - vm.$watch](#vm-watch)
## Options / DOM
### el
- **Type:** `string | Element`
- **Restriction:** only respected in instance creation via `new`.
- **Details:**
Provide the Vue instance an existing DOM element to mount on. It can be a CSS selector string or an actual HTMLElement.
After the instance is mounted, the resolved element will be accessible as `vm.$el`.
If this option is available at instantiation, the instance will immediately enter compilation; otherwise, the user will have to explicitly call `vm.$mount()` to manually start the compilation.
<p class="tip">The provided element merely serves as a mounting point. Unlike in Vue 1.x, the mounted element will be replaced with Vue-generated DOM in all cases. It is therefore not recommended to mount the root instance to `<html>` or `<body>`.</p>
<p class="tip">If neither `render` function nor `template` option is present, the in-DOM HTML of the mounting DOM element will be extracted as the template. In this case, Runtime + Compiler build of Vue should be used.</p>
- **See also:**
- [Lifecycle Diagram](../guide/instance.html#Lifecycle-Diagram)
- [Runtime + Compiler vs. Runtime-only](../guide/installation.html#Runtime-Compiler-vs-Runtime-only)
### template
- **Type:** `string`
- **Details:**
A string template to be used as the markup for the Vue instance. The template will **replace** the mounted element. Any existing markup inside the mounted element will be ignored, unless content distribution slots are present in the template.
If the string starts with `#` it will be used as a querySelector and use the selected element's innerHTML as the template string. This allows the use of the common `<script type="x-template">` trick to include templates.
<p class="tip">From a security perspective, you should only use Vue templates that you can trust. Never use user-generated content as your template.</p>
<p class="tip">If render function is present in the Vue option, the template will be ignored.</p>
- **See also:**
- [Lifecycle Diagram](../guide/instance.html#Lifecycle-Diagram)
- [Content Distribution with Slots](../guide/components.html#Content-Distribution-with-Slots)
### render
- **Type:** `(createElement: () => VNode) => VNode`
- **Details:**
An alternative to string templates allowing you to leverage the full programmatic power of JavaScript. The render function receives a `createElement` method as it's first argument used to create `VNode`s.
If the component is a functional component, the render function also receives an extra argument `context`, which provides access to contextual data since functional components are instance-less.
<p class="tip">The `render` function has priority over the render function compiled from `template` option or in-DOM HTML template of the mounting element which is specified by the `el` option.</p>
- **See also:** [Render Functions](../guide/render-function.html)
### renderError
> New in 2.2.0+
- **Type:** `(createElement: () => VNode, error: Error) => VNode`
- **Details:**
**Only works in development mode.**
Provide an alternative render output when the default `render` function encounters an error. The error will be passed to `renderError` as the second argument. This is particularly useful when used together with hot-reload.
- **Example:**
``` js
new Vue({
render (h) {
throw new Error('oops')
},
renderError (h, err) {
return h('pre', { style: { color: 'red' }}, err.stack)
}
}).$mount('#app')
```
- **See also:** [Render Functions](../guide/render-function.html)
## Options / Lifecycle Hooks
<p class="tip">All lifecycle hooks automatically have their `this` context bound to the instance, so that you can access data, computed properties, and methods. This means __you should not use an arrow function to define a lifecycle method__ (e.g. `created: () => this.fetchTodos()`). The reason is arrow functions bind the parent context, so `this` will not be the Vue instance as you expect and `this.fetchTodos` will be undefined.</p>
### beforeCreate
- **Type:** `Function`
- **Details:**
Called synchronously immediately after the instance has been initialized, before data observation and event/watcher setup.
- **See also:** [Lifecycle Diagram](../guide/instance.html#Lifecycle-Diagram)
### created
- **Type:** `Function`
- **Details:**
Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the `$el` property will not be available yet.
- **See also:** [Lifecycle Diagram](../guide/instance.html#Lifecycle-Diagram)
### beforeMount
- **Type:** `Function`
- **Details:**
Called right before the mounting begins: the `render` function is about to be called for the first time.
**This hook is not called during server-side rendering.**
- **See also:** [Lifecycle Diagram](../guide/instance.html#Lifecycle-Diagram)
### mounted
- **Type:** `Function`
- **Details:**
Called after the instance has been mounted, where `el` is replaced by the newly created `vm.$el`. If the root instance is mounted to an in-document element, `vm.$el` will also be in-document when `mounted` is called.
Note that `mounted` does **not** guarantee that all child components have also been mounted. If you want to wait until the entire view has been rendered, you can use [vm.$nextTick](#vm-nextTick) inside of `mounted`:
``` js
mounted: function () {
this.$nextTick(function () {
// Code that will run only after the
// entire view has been rendered
})
}
```
**This hook is not called during server-side rendering.**
- **See also:** [Lifecycle Diagram](../guide/instance.html#Lifecycle-Diagram)
### beforeUpdate
- **Type:** `Function`
- **Details:**
Called when data changes, before the DOM is patched. This is a good place to access the existing DOM before an update, e.g. to remove manually added event listeners.
**This hook is not called during server-side rendering, because only the initial render is performed server-side.**
- **See also:** [Lifecycle Diagram](../guide/instance.html#Lifecycle-Diagram)
### updated
- **Type:** `Function`
- **Details:**
Called after a data change causes the virtual DOM to be re-rendered and patched.
The component's DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here. However, in most cases you should avoid changing state inside the hook. To react to state changes, it's usually better to use a [computed property](#computed) or [watcher](#watch) instead.
Note that `updated` does **not** guarantee that all child components have also been re-rendered. If you want to wait until the entire view has been re-rendered, you can use [vm.$nextTick](#vm-nextTick) inside of `updated`:
``` js
updated: function () {
this.$nextTick(function () {
// Code that will run only after the
// entire view has been re-rendered
})
}
```
**This hook is not called during server-side rendering.**
- **See also:** [Lifecycle Diagram](../guide/instance.html#Lifecycle-Diagram)
### activated
- **Type:** `Function`
- **Details:**
Called when a kept-alive component is activated.
**This hook is not called during server-side rendering.**
- **See also:**
- [Built-in Components - keep-alive](#keep-alive)
- [Dynamic Components - keep-alive](../guide/components.html#keep-alive)
### deactivated
- **Type:** `Function`
- **Details:**
Called when a kept-alive component is deactivated.
**This hook is not called during server-side rendering.**
- **See also:**
- [Built-in Components - keep-alive](#keep-alive)
- [Dynamic Components - keep-alive](../guide/components.html#keep-alive)
### beforeDestroy
- **Type:** `Function`
- **Details:**
Called right before a Vue instance is destroyed. At this stage the instance is still fully functional.
**This hook is not called during server-side rendering.**
- **See also:** [Lifecycle Diagram](../guide/instance.html#Lifecycle-Diagram)
### destroyed
- **Type:** `Function`
- **Details:**
Called after a Vue instance has been destroyed. When this hook is called, all directives of the Vue instance have been unbound, all event listeners have been removed, and all child Vue instances have also been destroyed.
**This hook is not called during server-side rendering.**
- **See also:** [Lifecycle Diagram](../guide/instance.html#Lifecycle-Diagram)
### errorCaptured
> New in 2.5.0+
- **Type:** `(err: Error, vm: Component, info: string) => ?boolean`
- **Details:**
Called when an error from any descendent component is captured. The hook receives three arguments: the error, the component instance that triggered the error, and a string containing information on where the error was captured. The hook can return `false` to stop the error from propagating further.
<p class="tip">You can modify component state in this hook. However, it is important to have conditionals in your template or render function that short circuits other content when an error has been captured; otherwise the component will be thrown into an infinite render loop.</p>
**Error Propagation Rules**
- By default, all errors are still sent to the global `config.errorHandler` if it is defined, so that these errors can still be reported to an analytics service in a single place.
- If multiple `errorCaptured` hooks exist on a component's inheritance chain or parent chain, all of them will be invoked on the same error.
- If the `errorCaptured` hook itself throws an error, both this error and the original captured error are sent to the global `config.errorHandler`.
- An `errorCaptured` hook can return `false` to prevent the error from propagating further. This is essentially saying "this error has been handled and should be ignored." It will prevent any additional `errorCaptured` hooks or the global `config.errorHandler` from being invoked for this error.
## Options / Assets
### directives
- **Type:** `Object`
- **Details:**
A hash of directives to be made available to the Vue instance.
- **See also:** [Custom Directives](../guide/custom-directive.html)
### filters
- **Type:** `Object`
- **Details:**
A hash of filters to be made available to the Vue instance.
- **See also:** [`Vue.filter`](#Vue-filter)
### components
- **Type:** `Object`
- **Details:**
A hash of components to be made available to the Vue instance.
- **See also:** [Components](../guide/components.html)
## Options / Composition
### parent
- **Type:** `Vue instance`
- **Details:**
Specify the parent instance for the instance to be created. Establishes a parent-child relationship between the two. The parent will be accessible as `this.$parent` for the child, and the child will be pushed into the parent's `$children` array.