Ver Fonte

make vm.$get recursive

Evan You há 12 anos atrás
pai
commit
7b243950dc
2 ficheiros alterados com 15 adições e 3 exclusões
  1. 5 2
      src/viewmodel.js
  2. 10 1
      test/unit/specs/viewmodel.js

+ 5 - 2
src/viewmodel.js

@@ -28,8 +28,11 @@ var VMProto = ViewModel.prototype
  *  Convenience function to get a value from
  *  a keypath
  */
-def(VMProto, '$get', function (key, value) {
-    return utils.get(this, key, value)
+def(VMProto, '$get', function (key) {
+    var val = utils.get(this, key)
+    return val === undefined && this.$parent
+        ? this.$parent.$get(key)
+        : val
 })
 
 /**

+ 10 - 1
test/unit/specs/viewmodel.js

@@ -9,8 +9,12 @@ describe('ViewModel', function () {
             }
         },
         arr = [1, 2, 3],
+        parentVM = new Vue({
+            data: { fromParent: 'hello' }
+        }),
         vm = new Vue({
             el: '#vm-test',
+            parent: parentVM,
             data: {
                 a: data,
                 b: arr
@@ -18,10 +22,15 @@ describe('ViewModel', function () {
         })
 
     describe('.$get()', function () {
-        it('should set correct value', function () {
+        it('should get correct value', function () {
             var v = vm.$get('a.b.c')
             assert.strictEqual(v, 12345)
         })
+
+        it('should recursively get value from parents', function () {
+            var v = vm.$get('fromParent')
+            assert.strictEqual(v, 'hello')
+        })
     })
 
     describe('.$set()', function () {