index.js 1.5 KB

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