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

fix: ensure looseEqual is not dependant on key enumeration order

close #5908
Evan You 9 лет назад
Родитель
Сommit
a8ac129a58
2 измененных файлов с 48 добавлено и 4 удалено
  1. 20 4
      src/shared/util.js
  2. 28 0
      test/unit/features/directives/model-select.spec.js

+ 20 - 4
src/shared/util.js

@@ -248,15 +248,31 @@ export function genStaticKeys (modules: Array<ModuleOptions>): string {
  * Check if two values are loosely equal - that is,
  * if they are plain objects, do they have the same shape?
  */
-export function looseEqual (a: mixed, b: mixed): boolean {
+export function looseEqual (a: any, b: any): boolean {
+  if (a === b) return true
   const isObjectA = isObject(a)
   const isObjectB = isObject(b)
   if (isObjectA && isObjectB) {
     try {
-      return JSON.stringify(a) === JSON.stringify(b)
+      const isArrayA = Array.isArray(a)
+      const isArrayB = Array.isArray(b)
+      if (isArrayA && isArrayB) {
+        return a.length === b.length && a.every((e, i) => {
+          return looseEqual(e, b[i])
+        })
+      } else if (!isArrayA && !isArrayB) {
+        const keysA = Object.keys(a)
+        const keysB = Object.keys(b)
+        return keysA.length === keysB.length && keysA.every(key => {
+          return looseEqual(a[key], b[key])
+        })
+      } else {
+        /* istanbul ignore next */
+        return false
+      }
     } catch (e) {
-      // possible circular reference
-      return a === b
+      /* istanbul ignore next */
+      return false
     }
   } else if (!isObjectA && !isObjectB) {
     return String(a) === String(b)

+ 28 - 0
test/unit/features/directives/model-select.spec.js

@@ -119,6 +119,34 @@ describe('Directive v-model select', () => {
     }).then(done)
   })
 
+  it('should work with value bindings (Array loose equal)', done => {
+    const vm = new Vue({
+      data: {
+        test: [{ a: 2 }]
+      },
+      template:
+        '<select v-model="test">' +
+          '<option value="1">a</option>' +
+          '<option :value="[{ a: 2 }]">b</option>' +
+          '<option :value="[{ a: 3 }]">c</option>' +
+        '</select>'
+    }).$mount()
+    document.body.appendChild(vm.$el)
+    expect(vm.$el.childNodes[1].selected).toBe(true)
+    vm.test = [{ a: 3 }]
+    waitForUpdate(function () {
+      expect(vm.$el.childNodes[2].selected).toBe(true)
+
+      updateSelect(vm.$el, '1')
+      triggerEvent(vm.$el, 'change')
+      expect(vm.test).toBe('1')
+
+      updateSelect(vm.$el, [{ a: 2 }])
+      triggerEvent(vm.$el, 'change')
+      expect(vm.test).toEqual([{ a: 2 }])
+    }).then(done)
+  })
+
   it('should work with v-for', done => {
     const vm = new Vue({
       data: {