Просмотр исходного кода

allow v-repeat to work with numbers and strings

Evan You 11 лет назад
Родитель
Сommit
506cf13445
2 измененных файлов с 22 добавлено и 23 удалено
  1. 13 10
      src/directives/repeat.js
  2. 9 13
      test/unit/specs/directives/repeat_spec.js

+ 13 - 10
src/directives/repeat.js

@@ -133,7 +133,9 @@ module.exports = {
    */
 
   update: function (data) {
-    if (!data) return
+    if (typeof data === 'number') {
+      data = range(data)
+    }
     this.converted = data && data._converted
     this.vms = this.diff(data || [], this.vms)
     // update v-ref
@@ -455,16 +457,8 @@ function findNextVm (vm, ref) {
  */
 
 function objToArray (obj) {
-  if (_.isArray(obj)) {
-    return obj
-  }
-  if (obj == null) return
   if (!_.isPlainObject(obj)) {
-    _.warn(
-      'Invalid value for v-repeat: ' + obj +
-      '\nOnly Arrays and Objects are allowed.'
-    )
-    return
+    return obj
   }
   var keys = Object.keys(obj)
   var i = keys.length
@@ -479,4 +473,13 @@ function objToArray (obj) {
   }
   res._converted = true
   return res
+}
+
+function range (n) {
+  var i = -1
+  var ret = new Array(n)
+  while (++i < n) {
+    ret[i] = i
+  }
+  return ret
 }

+ 9 - 13
test/unit/specs/directives/repeat_spec.js

@@ -321,35 +321,31 @@ if (_.inBrowser) {
       expect(_.warn).toHaveBeenCalled()
     })
 
-    it('warn invalid data type', function () {
+    it('warn v-if', function () {
       var vm = new Vue({
         el: el,
-        template: '<div v-repeat="items"></div>',
+        template: '<div v-repeat="items" v-if="aaa"></div>',
         data: {
-          items: 1234
+          items: []
         }
       })
       expect(_.warn).toHaveBeenCalled()
     })
 
-    it('warn v-if', function () {
+    it('repeat number', function () {
       var vm = new Vue({
         el: el,
-        template: '<div v-repeat="items" v-if="aaa"></div>',
-        data: {
-          items: []
-        }
+        template: '<div v-repeat="3">{{$index}} {{$value}}</div>'
       })
-      expect(_.warn).toHaveBeenCalled()
+      expect(el.innerHTML).toBe('<div>0 0</div><div>1 1</div><div>2 2</div><!--v-repeat-->')
     })
 
-    it('falsy value', function () {
+    it('repeat string', function () {
       var vm = new Vue({
         el: el,
-        template: '<div v-repeat="items"></div>',
-        data: {}
+        template: '<div v-repeat="\'vue\'">{{$index}} {{$value}}</div>'
       })
-      expect(_.warn).not.toHaveBeenCalled()
+      expect(el.innerHTML).toBe('<div>0 v</div><div>1 u</div><div>2 e</div><!--v-repeat-->')
     })
 
     it('teardown', function () {