Vue.js实做星星评分功能

今天要来简单的实做星星评分的功能
在这项单元内也会简单的讲解到props$emit的传递
先附上成品图:
图一
先在components中新增一个Star的元件

    <div class="star_box">      <div class='star_line'>        <span class="star">☆</span>      </div>      <div class="star_line star_pointer">        <span class="star">★</span>      </div>    </div>

接着在views中也新增一个Products的组件
※请自行取得远端资料

再远端资料的物件中,新增一个star的值,并预设为0
图二
并将star组件import给Products
将取得的资料由外层传递给内层(使用props)
传递资料的属性名称,设为:product-item

<Star :product-item="item"></Star>

回到Star的组件中,先将星星的部分都给弄好
※做法为:做出两种星星,一组没颜色,一组有颜色,用有颜色的星星覆盖没颜色的星星
星星的总数量total预设为3颗(这里看你想要几颗星都行)

把外层:product-item的资料传递给props接收
在有颜色的星星上跑v-for迴圈,将物件中的star值给取出来
(还记得前面说的吗?在物件中新增一个star: 0 的值,因为我们要默认空白让顾客自行去评分)

接着再methods中命名一个changeValue的Function事件,并将其绑定@click事件在空白星星上,由@click="changeValue去接收total的参数
为了让星星分别绑定在个别商品上,因此我们要比对每样商品的id
所以我增加了const = starInfo的物件,将starid给塞了进去

  <div class="star_box">    <div class='star_line'>      <span        class="star"        v-for="(star, key) in total"        @click="changeValue(star)"        :style="starStyle"        :key="key"      >☆</span>    </div>    <div class="star_line star_pointer">      <span        class="star"        v-for="(star, key) in productItem.star"        :class="{'active': isActive}"        :style="starStyle"        :key="key"      >★</span>    </div>  </div><script>export default {  data () {    return {      isActive: true    }  },  props: {    total: {      default: 3    },    size: {      default: 30    },    productItem: {      type: Object    }  },  methods: {    changeValue (star) {      const starInfo = {        star,        id: this.productItem.id      }      this.$emit('update', starInfo)    }  },  computed: {    starStyle () {    //starStyle是计算星星的样式      return {        width: this.size + 'px',        height: this.size + 'px',        fontSize: this.size + 'px'      }    }  }}</script>

接下来透过$emitstar的资料传递给外层,因此将属性名称命名为update,并将starInfo给传递出去

<Star :product-item="item" @update="changeStar"></Star>

再外层(products)建立changeStar的Function,并接收内层所传递出来的starInfo
这时starInfo的资料应该是长成这样:
{id: "xxxxxxxxxxx", star: 0}
为了避免让新的star值去覆盖旧的star值
将物件依序经过 JSON.stringify 及 JSON.parse 两个方法,建立全新的物件
并且跑forEach迴圈,做完id的比对就大致上完成了

    changeStar (value) {      const newProducts = JSON.parse(JSON.stringify(this.products))      newProducts.forEach(item => {        if (item.id === value.id) {          item.star = value.star        }      })    }

结语
希望藉由这样的过程有帮助您更加理解星星评分的製作过程

那么今天的文章就到这啦,我们大家明天见~


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章