由于在写一个项目时候,遇到了要给服务进行评分的需求,所以写了一个星星评分组件,其效果如下:
实现代码如图所示:
<template>
<div>
<ul ref="star">
<li>☆</li>
<li>☆</li>
<li>☆</li>
<li>☆</li>
<li>☆</li>
</ul>
<span>{{test.score}}分</span>
</div>
</template>
<script>
import Vue from 'vue'
export default {
name: "star",
data(){
return{
test:{
score:0
}
}
},
methods:{
controlFun(){
const that = this;
let starArr = this.$refs.star.getElementsByTagName("li");
let mouseJudge = true;
let clickjudge = false;
for (let i = 0;i<starArr.length;i++){
starArr[i].index = i;
starArr[i].onmouseover = function () {
if (mouseJudge){
for (let j = 0; j<=this.index;j++){
starArr[j].className = 'act';
}
}
}
starArr[i].onmouseout = function () {
if (!clickjudge){
for (const star of starArr){
star.className = '';
}
}
}
starArr[i].onclick = function () {
mouseJudge = !mouseJudge
clickjudge = !clickjudge;
if (!mouseJudge){
Vue.set(that.test,'score',this.index+1)
}
}
}
}
},
mounted(){
this.controlFun();
}
}
</script>
<style scoped>
ul{
margin-right: 40px;
display: inline;
}
ul li{
display:inline;
margin:0 10px;
cursor:pointer;
}
.act{
color: #ff2a27;
}
</style>
比较需要注意的是,Vue 不允许在已经创建的实例上动态添加新的根级响应式属性 (root-level reactive property),所以想动态的更新分数,需要用到Vue.set()
|