Skip to content

Commit bf3ebcc

Browse files
committed
v-model: checkbox support array model
1 parent 88747b0 commit bf3ebcc

File tree

2 files changed

+33
-7
lines changed

2 files changed

+33
-7
lines changed

src/directive.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,9 @@ Directive.prototype._bind = function () {
130130
scope: this._scope
131131
}
132132
)
133-
if (this._initValue != null) {
133+
if (this.afterBind) {
134+
this.afterBind()
135+
} else if (this._initValue != null) {
134136
watcher.set(this._initValue)
135137
} else if (this.update) {
136138
this.update(watcher.value)

src/directives/model/checkbox.js

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ module.exports = {
2323
}
2424
}
2525

26-
function getValue () {
26+
function getBooleanValue () {
2727
var val = el.checked
2828
if (val && el.hasOwnProperty('_trueValue')) {
2929
return el._trueValue
@@ -40,16 +40,40 @@ module.exports = {
4040
return val
4141
}
4242

43-
this.on('change', function () {
44-
self.set(getValue())
45-
})
43+
this.listener = function () {
44+
var model = self._watcher.value
45+
if (_.isArray(model)) {
46+
var val = getValue(el)
47+
if (el.checked) {
48+
if (_.indexOf(model, val) < 0) {
49+
model.push(val)
50+
}
51+
} else {
52+
model.$remove(val)
53+
}
54+
} else {
55+
self.set(getBooleanValue())
56+
}
57+
}
58+
this.on('change', this.listener)
4659

4760
if (el.checked) {
48-
this._initValue = getValue()
61+
this.afterBind = this.listener
4962
}
5063
},
5164

5265
update: function (value) {
53-
this.el.checked = this._matchValue(value)
66+
var el = this.el
67+
if (_.isArray(value)) {
68+
el.checked = _.indexOf(value, getValue(el)) > -1
69+
} else {
70+
el.checked = this._matchValue(value)
71+
}
5472
}
5573
}
74+
75+
function getValue (el) {
76+
return el.hasOwnProperty('_value')
77+
? el._value
78+
: el.value
79+
}

0 commit comments

Comments
 (0)