vue 自定义组件 - 五星评分

2021-01-26  本文已影响0人  微笑中的你

无图无真相!!!


lz-star.gif

只能整数评分,未实现带小数,请自行实现!

开发环境

vue2.x

两张资源图片

xing.png xing2.png

组件 LzRoatingBar.vue

<template>
  <div class="wrapper">
    <div class="my-inbox" ref="box" @click.prevent="">
      <div
        v-for="index in 5"
        :key="index"
        :id="index"
        class="item"
        :class="{ active: index <= iSelect }"
        @click="clickOnItem(index)"
      ></div>
    </div>
  </div>
</template>

<script>
export default {
  name: "lz-roating-bar",
  props: {
    iScore: {
      type: Number,
      default: 5,
      validator: function(value) {
        return value >= 1 && value <= 5;
      }
    },
    isFloat: false,
    isEditable: false,
    
  },
  data() {
    return {
      score: this.getScore(),
      iSelect: this.iScore,
    };
  },

  methods: {
    clickOnItem(idx) {
      if (idx == this.iSelect) {
        return;
      }
      this.iSelect = idx;

      //更新数据
      this.$emit('update:iScore', this.getScore());
    },
    getScore() {
        return this.iSelect;
    },
  },
};
</script>

<style >
.wrapper {
  background-color: #f2f2f2;
  width: 100%;
}
.my-inbox {
  overflow-y: hidden;
  overflow-x: scroll;
  white-space: nowrap;
}
.item {
  display: inline-block;
  height: 2rem;
  width: 2rem;
  background-image: url(../assets/xing.png);
  background-position: center;
  background-repeat: no-repeat;
  background-size: 100%;
}
.active {
  background-image: url(../assets/xing2.png);
}
</style>

使用方法

<template>
  <div>
    <h1>测试自定义组件</h1>

    <!-- 使用.sync 进行数据的双向绑定 -->
    <lz-roating-bar :iScore.sync="score" />
    <div>当前评分为: {{ score }}</div>
  </div>
</template>

<script>
import LzRoatingBar from "../components/LzRoatingBar.vue";
export default {
  components: {
    LzRoatingBar,
  },

  data() {
    return {
      score: 1,
    };
  },
};
</script>

<style>
</style>

上一篇下一篇

猜你喜欢

热点阅读