基于vue编写的一个星星评分组件

由于在写一个项目时候,遇到了要给服务进行评分的需求,所以写了一个星星评分组件,其效果如下:

在这里插入图片描述
在这里插入图片描述
实现代码如图所示:

<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++){            //给所有li绑定事件

            starArr[i].index = i;
            starArr[i].onmouseover = function () {
              if (mouseJudge){
                for (let j = 0; j<=this.index;j++){           //this指向触发鼠标触碰事件的li,给该li及之前的li添加class属性
                  starArr[j].className = 'act';
                }
              }
            }

            starArr[i].onmouseout = function () {          //鼠标移开且未发生点击时,清除li的class属性
              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)     //只有存在li被选中的情况下才动态更新响应属性
            }
          }
        }
      }
    },

    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()

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值