-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathSwitch.jsx
124 lines (121 loc) · 2.93 KB
/
Switch.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import { switchPropTypes } from './PropTypes';
import BaseMixin from '../_util/BaseMixin';
import { hasProp, getOptionProps, getComponent } from '../_util/props-util';
import Omit from 'omit.js';
import { defineComponent } from 'vue';
// function noop () {
// }
export default defineComponent({
name: 'VcSwitch',
mixins: [BaseMixin],
inheritAttrs: false,
props: {
...switchPropTypes,
prefixCls: switchPropTypes.prefixCls.def('rc-switch'),
// onChange: switchPropTypes.onChange.def(noop),
// onClick: switchPropTypes.onClick.def(noop),
},
data() {
let checked = false;
if (hasProp(this, 'checked')) {
checked = !!this.checked;
} else {
checked = !!this.defaultChecked;
}
return {
stateChecked: checked,
};
},
watch: {
checked(val) {
this.stateChecked = val;
},
},
mounted() {
this.$nextTick(() => {
const { autofocus, disabled } = this;
if (autofocus && !disabled) {
this.focus();
}
});
},
methods: {
saveRef(c) {
this.refSwitchNode = c;
},
setChecked(checked, e) {
if (this.disabled) {
return;
}
if (!hasProp(this, 'checked')) {
this.stateChecked = checked;
}
this.__emit('update:checked', checked);
this.__emit('change', checked, e);
},
handleClick(e) {
const checked = !this.stateChecked;
this.setChecked(checked, e);
this.__emit('click', checked, e);
},
handleKeyDown(e) {
if (e.keyCode === 37) {
// Left
this.setChecked(false, e);
} else if (e.keyCode === 39) {
// Right
this.setChecked(true, e);
}
},
handleMouseUp(e) {
this.refSwitchNode?.blur();
this.__emit('mouseup', e);
},
focus() {
this.refSwitchNode?.focus();
},
blur() {
this.refSwitchNode?.blur();
},
},
render() {
const { prefixCls, disabled, loadingIcon, ...restProps } = getOptionProps(this);
const checked = this.stateChecked;
const { $attrs } = this;
const switchClassName = {
[$attrs.class]: $attrs.class,
[prefixCls]: true,
[`${prefixCls}-checked`]: checked,
[`${prefixCls}-disabled`]: disabled,
};
const spanProps = {
...Omit(restProps, [
'checkedChildren',
'unCheckedChildren',
'checked',
'autofocus',
'defaultChecked',
]),
...$attrs,
onKeydown: this.handleKeyDown,
onClick: this.handleClick,
onMouseup: this.handleMouseUp,
type: 'button',
role: 'switch',
'aria-checked': checked,
disabled,
class: switchClassName,
ref: this.saveRef,
};
return (
<button {...spanProps}>
{loadingIcon}
<span class={`${prefixCls}-inner`}>
{checked
? getComponent(this, 'checkedChildren')
: getComponent(this, 'unCheckedChildren')}
</span>
</button>
);
},
});