(五)写一个star组件,状态包括全亮、半亮、不亮3个状态
发布日期:2021-05-08 17:19:55 浏览次数:20 分类:精选文章

本文共 1727 字,大约阅读时间需要 5 分钟。

如何封装评价星星组件并实现动态显示

在前端开发中,评价星星组件是一个非常常见的需求。为了实现动态显示星星状态,我们可以通过以下步骤完成封装和数据传递。

准备星星图片素材 由于不同设备的像素不一致,准备不同尺寸的星星图片分别为24x24/36x36/48x48像素。全亮、半亮和不亮状态分别用on、half、off表示。

引入星星组件 在需要使用星星组件的.vue文件中,先引入star组件。例如,在header.vue文件中:

import star from '../star/star';

注册星星组件 在header.vue的script标签内,通过components属性注册star组件:

components: {
star
}

传递数据到子组件 在header.vue的template中引用star组件,并通过绑定自定义属性传递数据。传递的参数包括星星大小size和评分score:

接收父组件数据 在star.vue的script标签中,通过props对象声明接收的父组件数据:

export default {
props: {
size: {
type: Number
},
score: {
type: Number
}
}
}

计算星星状态 在star.vue中,通过computed属性计算星星的状态。根据评分score生成相应的星星个数和状态:

computed: {
starType() {
return `star-${this.size}`;
},
itemClasses() {
const LENGTH = 5;
const CLS_ON = 'on';
const CLS_HALF = 'half';
const CLS_OFF = 'off';
let score = Math.floor(this.score * 2) / 2;
const hasDecimal = score % 1 !== 0;
const integer = Math.floor(score);
const result = [];
for (let i = 0; i < integer; i++) {
result.push(CLS_ON);
}
if (hasDecimal) {
result.push(CLS_HALF);
}
while (result.length < LENGTH) {
result.push(CLS_OFF);
}
return result;
}
}

样式定义 在star.vue的style标签中定义不同尺寸星星的三种状态样式。例如:

.star {
font-size: 0;
}
.star-48 .star-item {
display: inline-block;
background-repeat: no-repeat;
width: 20px;
height: 20px;
margin-right: 22px;
background-size: 20px 20px;
&:last-child {
margin-right: 0;
}
&.on {
background-image: url('star48_on');
}
&.half {
background-image: url('star48_half');
}
&.off {
background-image: url('star48_off');
}
}

通过以上步骤,就可以实现评价星星组件的动态显示。前端通过调用star组件,并传递size和score参数,子组件根据计算结果动态生成并显示相应的星星状态。

上一篇:Java递归查询文件下所有的图片,移动到指定文件夹中,分批次建立子文件夹
下一篇:MySQL 表自连接,两次自连接查询

发表评论

最新留言

很好
[***.229.124.182]2025年05月17日 12时22分21秒