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

124 lines
2.6 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"
7 years ago
:index="i - 1"
7 years ago
:disabled="disabled"
:prefix-cls="`${prefixCls}-star`"
:allowHalf="allowHalf"
7 years ago
:value="hoverValue === undefined ? stateValue : hoverValue"
@click="onClick"
@hover="onHover"
:key="i - 1">
7 years ago
<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'
7 years ago
import Icon from '../icon'
import { getOffsetLeft } from './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,
},
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 {
hoverValue: undefined,
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) {
7 years ago
const value = this.getStarValue(index, event.pageX)
if (this.value === undefined) {
this.stateValue = value
}
7 years ago
this.onMouseLeave()
7 years ago
this.$emit('input', value)
this.$emit('change', value)
7 years ago
},
7 years ago
onHover (event, index) {
7 years ago
const value = this.getStarValue(index, event.pageX)
this.hoverValue = value
this.$emit('hover-change', value)
7 years ago
},
getStarDOM (index) {
return this.$refs.stars[index].$el
},
getStarValue (index, x) {
7 years ago
const { allowHalf, getStarDOM } = this
let value = index + 1
if (allowHalf) {
const leftEdge = getOffsetLeft(getStarDOM(0))
const width = getOffsetLeft(getStarDOM(1)) - leftEdge
if ((x - leftEdge - width * index) < width / 2) {
7 years ago
value -= 0.5
}
}
return value
},
7 years ago
onMouseLeave () {
7 years ago
if (this.disabled) return
this.hoverValue = undefined
this.$emit('hover-change')
7 years ago
},
},
watch: {
7 years ago
value (val) {
this.stateValue = val
7 years ago
},
},
components: {
Star,
Icon,
7 years ago
},
7 years ago
}
</script>