index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import baseComponent from '../helpers/baseComponent'
  2. import classNames from '../helpers/classNames'
  3. import eventsMixin from '../helpers/eventsMixin'
  4. import { isPresetColor } from '../helpers/colors'
  5. baseComponent({
  6. useField: true,
  7. behaviors: [eventsMixin()],
  8. relations: {
  9. '../field/index': {
  10. type: 'ancestor',
  11. },
  12. },
  13. properties: {
  14. prefixCls: {
  15. type: String,
  16. value: 'wux-switch',
  17. },
  18. value: {
  19. type: Boolean,
  20. value: false,
  21. observer(newVal) {
  22. if (this.hasFieldDecorator) return
  23. this.updated(newVal)
  24. },
  25. },
  26. disabled: {
  27. type: Boolean,
  28. value: false,
  29. },
  30. color: {
  31. type: String,
  32. value: 'balanced',
  33. observer: 'updateStyle',
  34. },
  35. },
  36. data: {
  37. inputStyle: '',
  38. inputChecked: false,
  39. },
  40. computed: {
  41. classes: ['prefixCls, inputChecked, disabled', function(prefixCls, inputChecked, disabled) {
  42. const wrap = classNames(prefixCls)
  43. const input = classNames(`${prefixCls}__input`, {
  44. [`${prefixCls}__input--checked`]: inputChecked,
  45. [`${prefixCls}__input--disabled`]: disabled,
  46. })
  47. return {
  48. wrap,
  49. input,
  50. }
  51. }],
  52. },
  53. methods: {
  54. updated(inputChecked) {
  55. if (this.data.inputChecked !== inputChecked) {
  56. this.setData({ inputChecked })
  57. }
  58. },
  59. onTap(e) {
  60. const { inputChecked, disabled } = this.data
  61. const newInputChecked = !inputChecked
  62. if (disabled) return
  63. this.triggerEvent('change', { value: newInputChecked })
  64. },
  65. updateStyle(color) {
  66. const newColor = isPresetColor(color)
  67. const inputStyle = `border-color: ${newColor}; background-color: ${newColor};`
  68. this.setData({ inputStyle })
  69. },
  70. },
  71. attached() {
  72. this.updateStyle(this.data.color)
  73. },
  74. })