index.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import baseComponent from '../helpers/baseComponent'
  2. import classNames from '../helpers/libs/classNames'
  3. import eventsMixin from '../helpers/mixins/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. loading: {
  31. type: Boolean,
  32. value: false,
  33. },
  34. color: {
  35. type: String,
  36. value: 'balanced',
  37. observer: 'updateStyle',
  38. },
  39. checkedText: {
  40. type: String,
  41. value: '',
  42. },
  43. uncheckedText: {
  44. type: String,
  45. value: '',
  46. },
  47. },
  48. data: {
  49. inputStyle: '',
  50. inputChecked: false,
  51. },
  52. computed: {
  53. classes: ['prefixCls, inputChecked, disabled, loading, color', function(prefixCls, inputChecked, disabled, loading, color) {
  54. const wrap = classNames(prefixCls, {
  55. [`${prefixCls}--${color}`]: color,
  56. [`${prefixCls}--checked`]: inputChecked,
  57. [`${prefixCls}--disabled`]: disabled || loading,
  58. })
  59. const input = classNames(`${prefixCls}__input`, {
  60. [`${prefixCls}__input--checked`]: inputChecked,
  61. [`${prefixCls}__input--disabled`]: disabled || loading,
  62. })
  63. const text = `${prefixCls}__text`
  64. const spin = `${prefixCls}__spin`
  65. return {
  66. wrap,
  67. input,
  68. text,
  69. spin,
  70. }
  71. }],
  72. },
  73. methods: {
  74. updated(inputChecked) {
  75. if (this.data.inputChecked !== inputChecked) {
  76. this.setData({ inputChecked })
  77. }
  78. },
  79. onTap(e) {
  80. const { inputChecked, disabled, loading } = this.data
  81. const newInputChecked = !inputChecked
  82. if (disabled || loading) return
  83. this.triggerEvent('change', { value: newInputChecked })
  84. },
  85. updateStyle(color) {
  86. const newColor = isPresetColor(color)
  87. const inputStyle = `border-color: ${newColor}; background-color: ${newColor};`
  88. this.setData({ inputStyle })
  89. },
  90. },
  91. attached() {
  92. this.updateStyle(this.data.color)
  93. },
  94. })