also catch error in data() (close #5198)

This commit is contained in:
Evan You 2017-03-17 11:46:37 +08:00
parent 26f196780c
commit 59a372229b
2 changed files with 27 additions and 6 deletions

View File

@ -7,18 +7,19 @@ import {
set,
del,
observe,
defineReactive,
observerState
observerState,
defineReactive
} from '../observer/index'
import {
warn,
bind,
noop,
hasOwn,
isReserved,
isPlainObject,
bind,
handleError,
validateProp,
noop
isPlainObject
} from '../util/index'
const sharedPropertyDefinition = {
@ -101,7 +102,7 @@ function initProps (vm: Component, propsOptions: Object) {
function initData (vm: Component) {
let data = vm.$options.data
data = vm._data = typeof data === 'function'
? data.call(vm)
? getData(data, vm)
: data || {}
if (!isPlainObject(data)) {
data = {}
@ -130,6 +131,15 @@ function initData (vm: Component) {
observe(data, true /* asRootData */)
}
function getData (data: Function, vm: Component): any {
try {
return data.call(vm)
} catch (e) {
handleError(e, vm, `data()`)
return {}
}
}
const computedWatcherOptions = { lazy: true }
function initComputed (vm: Component, computed: Object) {

View File

@ -7,6 +7,7 @@ describe('Error handling', () => {
// hooks that prevents the component from rendering, but should not
// break parent component
;[
['data', 'data()'],
['render', 'render function'],
['beforeCreate', 'beforeCreate hook'],
['created', 'created hook'],
@ -128,6 +129,16 @@ describe('Error handling', () => {
function createErrorTestComponents () {
const components = {}
// data
components.data = {
data () {
throw new Error('data')
},
render (h) {
return h('div')
}
}
// render error
components.render = {
render (h) {