You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ant-design-vue/components/rate/Rate.vue

135 lines
2.8 KiB

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