8fc47d9878e7b2bd246a9fbecc6fda43565bce2527c0d5d377993aba427716423585059c6c4f58b913ca91673eb306b5793b09fb44f79651e4056e1761a423 1.2 KB

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