Skip to content

Commit

Permalink
fix: ensure looseEqual is not dependant on key enumeration order
Browse files Browse the repository at this point in the history
close #5908
  • Loading branch information
yyx990803 committed Jul 21, 2017
1 parent 9b4dbba commit a8ac129
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 4 deletions.
24 changes: 20 additions & 4 deletions src/shared/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
28 changes: 28 additions & 0 deletions test/unit/features/directives/model-select.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down

0 comments on commit a8ac129

Please sign in to comment.