用vue写星星评分

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./vue.js"></script>
    <style>
      .root {
        position: relative;
        border: 1px solid red;
        margin-top: 20px;
      }
      .full {
        position: absolute;
        top: 0;
        left: 0;
        overflow: hidden;
      }
    
    </style>
  </head>
  <body>
    <div id="app">
      <input type="text" v-model.number="score" placeholder="输入评分" />
      <hr />
      <star v-model="score" :count="5" :size="20"></star>
      <star v-model="score" :count="7" :size="30"></star>
      <star v-model="score" :count="10" :size="40"></star>
    </div>

    <template id="star">
      <div class="root" :style="rootStyle">
        <div class="empty">
          <img
            :style="imgStyle"
            v-for="i in count"
            :key="i"
            src="./s2.png"
            alt=""
            @click="starClick(i)"
          />
        </div>
        <div class="full" :style="fullStyle">
          <img
            :style="imgStyle"
            v-for="i in count"
            :key="i"
            src="./s1.png"
            alt=""
            @click="starClick(i)"
          />
        </div>
      </div>
    </template>
    <script>
      let star = {
        template: "#star",
        data: function () {
          return {};
        },

        props: {
          value: Number, //星星的分数
          count: Number, //星星数量
          size: Number, // 星星的尺寸
        },
        methods: {
          starClick(i) {
            //修改 score值
            this.$emit("input", i);
          },
        },
        computed: {
          rootStyle() {
            return {
              width: this.count * this.size + "px",
              height: this.size + "px",
            };
          },
          imgStyle() {
            return {
              width: this.size + "px",
            };
          },
          fullStyle() {
            return {
              width: this.value * this.size + "px",
              height: this.size + "px",
            };
          },
        },
      };
      let vm = new Vue({
        el: "#app",
        data: {
          score: 2,
        },
        components: {
          star,
        },
      });
    </script>
  </body>
</html>
 
效果如下:

 

 

posted @ 2020-12-17 17:21  阳菜  阅读(295)  评论(0)    收藏  举报