index.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. Component({
  2. mixins: [],
  3. data: {
  4. bgcolor: '#fff',
  5. bdcolor: '#ccc'
  6. },
  7. props: {
  8. disabled: false, // 是否禁用
  9. checked: false, // 是否选中
  10. fieldKey:'',
  11. color: "rgba(61, 115, 255, 1)", // 激活状态颜色
  12. type: "capsule" // 默认胶囊状 capsule,可选:方形 square
  13. },
  14. didUpdate(newVal, oldVal) {
  15. console.log('didUpdate',newVal, oldVal)
  16. if (newVal.checked !== oldVal.checked){
  17. this.changeColor()
  18. }
  19. },
  20. didMount() {
  21. this.changeColor()
  22. },
  23. didUnmount() { },
  24. methods: {
  25. changeColor(){
  26. let checked = false;
  27. if (this.props.checked) {
  28. checked = true;
  29. } else {
  30. checked = false;
  31. }
  32. this.setData({
  33. checked: checked
  34. })
  35. if (this.data.checked) {
  36. this.setData({
  37. bgcolor: this.props.color,
  38. bdcolor: this.props.color
  39. })
  40. }else {
  41. this.setData({
  42. bgcolor: '#fff',
  43. bdcolor: '#fff'
  44. })
  45. }
  46. },
  47. handleSwitch(e) {
  48. if (!this.props.disabled || this.props.disabled === 'false') {
  49. this.setData({
  50. checked: !e.currentTarget.dataset.checked
  51. })
  52. if (this.data.checked) {
  53. this.setData({
  54. bgcolor: this.props.color,
  55. bdcolor: this.props.color
  56. })
  57. } else {
  58. this.setData({
  59. bgcolor: "#fff",
  60. bdcolor: "#ccc"
  61. })
  62. }
  63. if (this.props.onChange) {
  64. this.props.onChange(this.props.fieldKey, this.data.checked);
  65. }
  66. }
  67. }
  68. },
  69. });