element/packages/radio/src/radio-group.vue

99 lines
2.4 KiB
Vue
Raw Normal View History

<template>
2017-07-26 13:24:23 +00:00
<div
class="el-radio-group"
role="radiogroup"
@keydown="handleKeydown"
>
<slot></slot>
</div>
</template>
2016-07-27 06:15:02 +00:00
<script>
2016-10-27 09:31:22 +00:00
import Emitter from 'element-ui/src/mixins/emitter';
2016-07-27 06:15:02 +00:00
2017-07-26 13:24:23 +00:00
const keyCode = Object.freeze({
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
});
2016-07-27 06:15:02 +00:00
export default {
name: 'ElRadioGroup',
componentName: 'ElRadioGroup',
2016-08-15 02:36:21 +00:00
2017-10-12 09:50:06 +00:00
inject: ['elFormItem'],
2016-10-27 09:31:22 +00:00
mixins: [Emitter],
2016-07-27 06:15:02 +00:00
props: {
value: {},
2016-11-26 09:54:27 +00:00
size: String,
fill: String,
textColor: String,
disabled: Boolean
2016-07-27 06:15:02 +00:00
},
2017-10-12 09:50:06 +00:00
computed: {
_elFormItemSize() {
return (this.elFormItem || {}).elFormItemSize;
},
radioGroupSize() {
return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
}
},
created() {
this.$on('handleChange', value => {
this.$emit('change', value);
});
},
2017-07-26 13:24:23 +00:00
mounted() {
// 当radioGroup没有默认选项时第一个可以选中Tab导航
let radios = this.$el.querySelectorAll('[type=radio]');
if (![].some.call(radios, radio => radio.checked)) {
this.$el.querySelectorAll('[role=radio]')[0].tabIndex = 0;
}
},
methods: {
handleKeydown(e) { // 左右上下按键 可以在radio组内切换不同选项
const target = e.target;
const className = target.nodeName === 'INPUT' ? '[type=radio]' : '[role=radio]';
const radios = this.$el.querySelectorAll(className);
const length = radios.length;
const index = [].indexOf.call(radios, target);
const roleRadios = this.$el.querySelectorAll('[role=radio]');
switch (e.keyCode) {
case keyCode.LEFT:
case keyCode.UP:
e.stopPropagation();
e.preventDefault();
if (index === 0) {
roleRadios[length - 1].click();
} else {
roleRadios[index - 1].click();
}
break;
case keyCode.RIGHT:
case keyCode.DOWN:
if (index === (length - 1)) {
e.stopPropagation();
e.preventDefault();
roleRadios[0].click();
} else {
roleRadios[index + 1].click();
}
break;
default:
break;
}
}
},
2016-07-27 06:15:02 +00:00
watch: {
value(value) {
2016-11-26 07:18:38 +00:00
this.dispatch('ElFormItem', 'el.form.change', [this.value]);
2016-07-27 06:15:02 +00:00
}
}
};
</script>