Skip to content

Commit 59a3722

Browse files
committed
also catch error in data() (close vuejs#5198)
1 parent 26f1967 commit 59a3722

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

src/core/instance/state.js

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,19 @@ import {
77
set,
88
del,
99
observe,
10-
defineReactive,
11-
observerState
10+
observerState,
11+
defineReactive
1212
} from '../observer/index'
1313

1414
import {
1515
warn,
16+
bind,
17+
noop,
1618
hasOwn,
1719
isReserved,
18-
isPlainObject,
19-
bind,
20+
handleError,
2021
validateProp,
21-
noop
22+
isPlainObject
2223
} from '../util/index'
2324

2425
const sharedPropertyDefinition = {
@@ -101,7 +102,7 @@ function initProps (vm: Component, propsOptions: Object) {
101102
function initData (vm: Component) {
102103
let data = vm.$options.data
103104
data = vm._data = typeof data === 'function'
104-
? data.call(vm)
105+
? getData(data, vm)
105106
: data || {}
106107
if (!isPlainObject(data)) {
107108
data = {}
@@ -130,6 +131,15 @@ function initData (vm: Component) {
130131
observe(data, true /* asRootData */)
131132
}
132133

134+
function getData (data: Function, vm: Component): any {
135+
try {
136+
return data.call(vm)
137+
} catch (e) {
138+
handleError(e, vm, `data()`)
139+
return {}
140+
}
141+
}
142+
133143
const computedWatcherOptions = { lazy: true }
134144

135145
function initComputed (vm: Component, computed: Object) {

test/unit/features/error-handling.spec.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ describe('Error handling', () => {
77
// hooks that prevents the component from rendering, but should not
88
// break parent component
99
;[
10+
['data', 'data()'],
1011
['render', 'render function'],
1112
['beforeCreate', 'beforeCreate hook'],
1213
['created', 'created hook'],
@@ -128,6 +129,16 @@ describe('Error handling', () => {
128129
function createErrorTestComponents () {
129130
const components = {}
130131

132+
// data
133+
components.data = {
134+
data () {
135+
throw new Error('data')
136+
},
137+
render (h) {
138+
return h('div')
139+
}
140+
}
141+
131142
// render error
132143
components.render = {
133144
render (h) {

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy