Browse Source

copy props when replacing $data (fix vuejs/Discussion#173)

Evan You 11 năm trước cách đây
mục cha
commit
949ada9cd1
2 tập tin đã thay đổi với 35 bổ sung0 xóa
  1. 9 0
      src/instance/scope.js
  2. 26 0
      test/unit/specs/instance/scope_spec.js

+ 9 - 0
src/instance/scope.js

@@ -59,6 +59,15 @@ exports._setData = function (newData) {
   var oldData = this._data
   this._data = newData
   var keys, key, i
+  // copy props
+  var props = this.$options.props
+  if (props) {
+    i = props.length
+    while (i--) {
+      key = props[i]
+      newData.$set(key, oldData[key])
+    }
+  }
   // unproxy keys not present in new data
   keys = Object.keys(oldData)
   i = keys.length

+ 26 - 0
test/unit/specs/instance/scope_spec.js

@@ -31,6 +31,32 @@ describe('Instance Scope', function () {
 
   })
 
+  describe('$data', function () {
+
+    var vm = new Vue({
+      props: ['c'],
+      data: {
+        a: 1
+      }
+    })
+
+    it('should initialize props', function () {
+      expect(vm.hasOwnProperty('c')).toBe(true)
+    })
+
+    it('replace $data', function () {
+      vm.c = 3
+      vm.$data = { b: 2 }
+      // proxy new key
+      expect(vm.b).toBe(2)
+      // unproxy old key that's no longer present
+      expect(vm.hasOwnProperty('a')).toBe(false)
+      // should copy props
+      expect(vm.c).toBe(3)
+    })
+
+  })
+
   describe('computed', function () {
     
     var Test = Vue.extend({