iview/src/components/switch/switch.vue

100 lines
2.9 KiB
Vue
Raw Normal View History

2016-09-09 14:29:19 +08:00
<template>
2018-02-07 09:02:32 +01:00
<span
tabindex="0"
:class="wrapClasses"
@click="toggle"
@keydown.space="toggle"
>
2017-09-19 16:45:02 +08:00
<input type="hidden" :name="name" :value="currentValue">
2016-09-09 14:29:19 +08:00
<span :class="innerClasses">
2017-09-07 11:19:19 +08:00
<slot name="open" v-if="currentValue === trueValue"></slot>
<slot name="close" v-if="currentValue === falseValue"></slot>
2016-09-09 14:29:19 +08:00
</span>
</span>
</template>
<script>
import { oneOf } from '../../utils/assist';
import Emitter from '../../mixins/emitter';
2016-09-09 14:29:19 +08:00
const prefixCls = 'ivu-switch';
export default {
2017-12-18 14:23:53 +08:00
name: 'iSwitch',
mixins: [ Emitter ],
2016-09-09 14:29:19 +08:00
props: {
2017-03-02 11:19:00 +08:00
value: {
2017-09-03 10:59:23 +08:00
type: [String, Number, Boolean],
default: false
},
trueValue: {
type: [String, Number, Boolean],
default: true
},
falseValue: {
type: [String, Number, Boolean],
2016-09-09 14:29:19 +08:00
default: false
},
disabled: {
type: Boolean,
default: false
},
size: {
validator (value) {
2017-08-25 10:53:52 +08:00
return oneOf(value, ['large', 'small', 'default']);
2016-09-09 14:29:19 +08:00
}
2017-09-19 16:45:02 +08:00
},
name: {
type: String
2018-06-22 10:14:13 +08:00
},
loading: {
type: Boolean,
default: false
2016-09-09 14:29:19 +08:00
}
},
2017-03-02 11:19:00 +08:00
data () {
return {
currentValue: this.value
2017-03-02 11:50:02 +08:00
};
2017-03-02 11:19:00 +08:00
},
2016-09-09 14:29:19 +08:00
computed: {
wrapClasses () {
return [
`${prefixCls}`,
{
2017-09-07 11:19:19 +08:00
[`${prefixCls}-checked`]: this.currentValue === this.trueValue,
2016-09-09 14:29:19 +08:00
[`${prefixCls}-disabled`]: this.disabled,
2018-06-22 10:14:13 +08:00
[`${prefixCls}-${this.size}`]: !!this.size,
[`${prefixCls}-loading`]: this.loading,
2016-09-09 14:29:19 +08:00
}
2016-12-25 22:49:42 +08:00
];
2016-09-09 14:29:19 +08:00
},
innerClasses () {
return `${prefixCls}-inner`;
}
},
methods: {
2018-03-05 09:18:23 +08:00
toggle (event) {
event.preventDefault();
2018-06-22 10:14:13 +08:00
if (this.disabled || this.loading) {
2016-09-09 14:29:19 +08:00
return false;
}
2017-09-03 10:59:23 +08:00
const checked = this.currentValue === this.trueValue ? this.falseValue : this.trueValue;
2017-03-02 11:19:00 +08:00
this.currentValue = checked;
this.$emit('input', checked);
this.$emit('on-change', checked);
this.dispatch('FormItem', 'on-form-change', checked);
2017-03-02 11:19:00 +08:00
}
},
watch: {
value (val) {
2017-09-03 10:59:23 +08:00
if (val !== this.trueValue && val !== this.falseValue) {
throw 'Value should be trueValue or falseValue.';
}
2017-03-02 11:19:00 +08:00
this.currentValue = val;
2016-09-09 14:29:19 +08:00
}
}
2016-12-25 22:49:42 +08:00
};
</script>