今天要来简单的实做星星评分的功能
在这项单元内也会简单的讲解到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
的物件,将star
和id
给塞了进去
<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>
接下来透过$emit
将star
的资料传递给外层,因此将属性名称命名为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 } }) }
结语
希望藉由这样的过程有帮助您更加理解星星评分的製作过程
那么今天的文章就到这啦,我们大家明天见~