ant-design-vue/components/rate/Rate.vue

129 lines
2.7 KiB
Vue
Raw Normal View History

2017-11-01 09:03:42 +00:00
<template>
<ul
:class="[prefixCls, disabled ? `${prefixCls}-disabled` : '', className]"
@mouseleave="onMouseLeave">
<template v-for="i in count">
<Star
ref="stars"
:index="i"
:disabled="disabled"
:prefix-cls="`${prefixCls}-star`"
:allowHalf="allowHalf"
:value="currentValue"
@onClick="onClick"
@onHover="onHover"
:key="i">
<template slot-scope="props">
<slot>
2017-11-02 02:56:18 +00:00
<span v-html="character"></span>
2017-11-01 09:03:42 +00:00
</slot>
</template>
</Star>
</template>
</ul>
</template>
<script>
2017-11-02 02:56:18 +00:00
import Vue from 'vue';
2017-11-01 09:03:42 +00:00
import Star from './Star.vue';
import Icon from '../icon/index';
import { getOffsetLeft } from '../util/util';
export default {
name: 'Rate',
props: {
count: {
type: Number,
default: 5,
},
value: {
type: Number,
default: 0,
},
defaultValue: {
type: Number,
default: 0,
},
onChange: {
type: Function,
default: () => {},
},
onHoverChange: {
type: Function,
default: () => {},
},
allowHalf: {
type: Boolean,
default: false,
},
disabled: {
type: Boolean,
default: false,
},
2017-11-02 02:56:18 +00:00
character: {
type: String,
default: '★'
},
2017-11-01 09:03:42 +00:00
className: String,
},
data() {
2017-11-02 02:56:18 +00:00
const reValue = this.value || this.defaultValue;
2017-11-01 09:03:42 +00:00
return {
prefixCls: 'ant-rate',
hoverValue: undefined,
2017-11-02 02:56:18 +00:00
currentValue: reValue,
markValue: reValue,
2017-11-01 09:03:42 +00:00
}
},
watch: {
hoverValue(val) {
if(val === undefined) {
this.currentValue = this.markValue;
return;
}
this.currentValue = val;
2017-11-02 02:56:18 +00:00
},
value() {
this.currentValue = this.markValue = this.value || this.defaultValue;
},
markValue(val) {
this.$emit('input', val);
2017-11-01 09:03:42 +00:00
}
},
methods: {
onClick(event, index) {
let clValue = this.getStarValue(index, event.pageX);
this.markValue = clValue;
this.onMouseLeave();
this.onChange(clValue);
},
onHover(event, index) {
this.hoverValue = this.getStarValue(index, event.pageX);
this.onHoverChange(this.hoverValue);
},
getStarDOM (index) {
return this.$refs.stars[index].$el
},
getStarValue (index, x) {
let value = index;
if (this.allowHalf) {
const leftEdge = getOffsetLeft(this.getStarDOM(0))
const width = getOffsetLeft(this.getStarDOM(1)) - leftEdge
if ((x - leftEdge - width * (index-1)) < width / 2) {
value -= 0.5
}
}
return value
},
onMouseLeave() {
this.hoverValue = undefined
this.onHoverChange(undefined);
},
},
components: {
Star,
Icon,
}
}
</script>