소스 검색

return object for v-ref on v-repeat with object value

Evan You 11 년 전
부모
커밋
67f017f236
2개의 변경된 파일44개의 추가작업 그리고 1개의 파일을 삭제
  1. 19 1
      src/directives/repeat.js
  2. 25 0
      test/unit/specs/directives/ref_spec.js

+ 19 - 1
src/directives/repeat.js

@@ -209,7 +209,9 @@ module.exports = {
     this.vms = this.diff(data, this.vms)
     // update v-ref
     if (this.refID) {
-      this.vm.$[this.refID] = this.vms
+      this.vm.$[this.refID] = this.converted
+        ? toRefObject(this.vms)
+        : this.vms
     }
     if (this.elId) {
       this.vm.$$[this.elId] = this.vms.map(function (vm) {
@@ -609,4 +611,20 @@ function range (n) {
     ret[i] = i
   }
   return ret
+}
+
+/**
+ * Convert a vms array to an object ref for v-ref on an
+ * Object value.
+ *
+ * @param {Array} vms
+ * @return {Object}
+ */
+
+function toRefObject (vms) {
+  var ref = {}
+  for (var i = 0, l = vms.length; i < l; i++) {
+    ref[vms[i].$key] = vms[i]
+  }
+  return ref
 }

+ 25 - 0
test/unit/specs/directives/ref_spec.js

@@ -94,6 +94,31 @@ if (_.inBrowser) {
       })
     })
 
+    it('object v-repeat', function (done) {
+      var vm = new Vue({
+        el: el,
+        data: {
+          items: {
+            a: 1,
+            b: 2
+          }
+        },
+        template: '<div v-repeat="items" v-ref="test"></div>'
+      })
+      expect(vm.$.test).toBeTruthy()
+      expect(_.isPlainObject(vm.$.test)).toBe(true)
+      expect(vm.$.test.a.$value).toBe(1)
+      expect(vm.$.test.b.$value).toBe(2)
+      vm.items = { c: 3 }
+      _.nextTick(function () {
+        expect(Object.keys(vm.$.test).length).toBe(1)
+        expect(vm.$.test.c.$value).toBe(3)
+        vm._directives[0].unbind()
+        expect(vm.$.test).toBeNull()
+        done()
+      })
+    })
+
     it('nested v-repeat', function () {
       var vm = new Vue({
         el: el,