model.js
1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* @flow */
import { looseEqual, looseIndexOf } from 'shared/util'
// this is only applied for <select v-model> because it is the only edge case
// that must be done at runtime instead of compile time.
export default function model (node: VNodeWithData, dir: VNodeDirective) {
if (!node.children) return
const value = dir.value
const isMultiple = node.data.attrs && node.data.attrs.multiple
for (let i = 0, l = node.children.length; i < l; i++) {
const option = node.children[i]
if (option.tag === 'option') {
if (isMultiple) {
const selected =
Array.isArray(value) &&
(looseIndexOf(value, getValue(option)) > -1)
if (selected) {
setSelected(option)
}
} else {
if (looseEqual(value, getValue(option))) {
setSelected(option)
return
}
}
}
}
}
function getValue (option) {
const data = option.data || {}
return (
(data.attrs && data.attrs.value) ||
(data.domProps && data.domProps.value) ||
(option.children && option.children[0] && option.children[0].text)
)
}
function setSelected (option) {
const data = option.data || (option.data = {})
const attrs = data.attrs || (data.attrs = {})
attrs.selected = ''
}