Explorar o código

warn empty data functions

Evan You %!s(int64=10) %!d(string=hai) anos
pai
achega
458982c3ff
Modificáronse 2 ficheiros con 15 adicións e 1 borrados
  1. 8 1
      src/instance/internal/state.js
  2. 7 0
      test/unit/specs/instance/state_spec.js

+ 8 - 1
src/instance/internal/state.js

@@ -11,6 +11,7 @@ import {
   query,
   hasOwn,
   isReserved,
+  isPlainObject,
   bind
 } from '../../util/index'
 
@@ -76,7 +77,13 @@ export default function (Vue) {
 
   Vue.prototype._initData = function () {
     var dataFn = this.$options.data
-    var data = this._data = dataFn ? dataFn() || {} : {}
+    var data = this._data = dataFn ? dataFn() : {}
+    if (!isPlainObject(data)) {
+      data = {}
+      process.env.NODE_ENV !== 'production' && warn(
+        'data functions should return an object.'
+      )
+    }
     var props = this._props
     var runtimeData = this._runtimeData
       ? typeof this._runtimeData === 'function'

+ 7 - 0
test/unit/specs/instance/state_spec.js

@@ -2,6 +2,13 @@ var Vue = require('src')
 var _ = require('src/util')
 
 describe('Instance state initialization', function () {
+  it('should warn data functions that do not return an object', function () {
+    new Vue({
+      data: function () {}
+    })
+    expect('should return an object').toHaveBeenWarned()
+  })
+
   describe('data proxy', function () {
     var data = {
       a: 0,