Browse Source

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

Evan You 9 years ago
parent
commit
59a372229b
2 changed files with 27 additions and 6 deletions
  1. 16 6
      src/core/instance/state.js
  2. 11 0
      test/unit/features/error-handling.spec.js

+ 16 - 6
src/core/instance/state.js

@@ -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) {

+ 11 - 0
test/unit/features/error-handling.spec.js

@@ -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) {