Skip to content

Commit 9e38abc

Browse files
defccyyx990803
authored andcommitted
Support select multiple binding (fix #4755) (#4756)
* support select multiple binding * improve select onchange handle * update style
1 parent 466e849 commit 9e38abc

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

src/platforms/web/compiler/directives/model.js

+5-4
Original file line numberDiff line numberDiff line change
@@ -163,13 +163,14 @@ function genSelect (
163163
}
164164

165165
const number = modifiers && modifiers.number
166-
const assignment = `Array.prototype.filter` +
166+
const selectedVal = `Array.prototype.filter` +
167167
`.call($event.target.options,function(o){return o.selected})` +
168168
`.map(function(o){var val = "_value" in o ? o._value : o.value;` +
169-
`return ${number ? '_n(val)' : 'val'}})` +
170-
(el.attrsMap.multiple == null ? '[0]' : '')
169+
`return ${number ? '_n(val)' : 'val'}})`
171170

172-
const code = genAssignmentCode(value, assignment)
171+
const assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'
172+
let code = `var $$selectedVal = ${selectedVal};`
173+
code = `${code} ${genAssignmentCode(value, assignment)}`
173174
addHandler(el, 'change', code, null, true)
174175
}
175176

test/unit/features/directives/model-select.spec.js

+25
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,31 @@ describe('Directive v-model select', () => {
262262
})
263263
}
264264

265+
it('should work with multiple binding', (done) => {
266+
const spy = jasmine.createSpy()
267+
const vm = new Vue({
268+
data: {
269+
isMultiple: true,
270+
selections: ['1']
271+
},
272+
template:
273+
'<select v-model="selections" :multiple="isMultiple">' +
274+
'<option value="1">item 1</option>' +
275+
'<option value="2">item 2</option>' +
276+
'</select>',
277+
watch: {
278+
selections: spy
279+
}
280+
}).$mount()
281+
document.body.appendChild(vm.$el)
282+
vm.$el.options[1].selected = true
283+
triggerEvent(vm.$el, 'change')
284+
waitForUpdate(() => {
285+
expect(spy).toHaveBeenCalled()
286+
expect(vm.selections).toEqual(['1', '2'])
287+
}).then(done)
288+
})
289+
265290
it('multiple with static template', () => {
266291
const vm = new Vue({
267292
template:

0 commit comments

Comments
 (0)