Vue.js 点击星星进行评价

1、评价等级(1、2、3、4、5)星

2、支持显示平均评价半星,不支持评价点击星星的时候半星

效果如图:

初始化显示:



点击星星显示:



步骤

CSC:添加一个显示全星,半星,空星的样式

JS: 如下,自定义一个组件

const LENGTH = 5;
const CLS_ON = 'icon-grade-full'; // 全星
const CLS_HALF = 'icon-grade-half'; // 半星
const CLS_OFF = 'icon-grade-empty'; // 空星
Vue.component('star-evaluation', {
  template: `
`
, props: { //* propScore: { // 传入的变量 type: Number } }, data: function () { return { score: '' } }, methods: { selectStar: function (index, event) { console.log(event.target) // 点击当前星星索引值+1 this.score = index + 1; } }, computed: { //* 计算显示星星 itemClasses () { let result = []; // 返回的是一个数组,用来遍历输出星星 let score = Math.floor(this.score * 2) / 2; // 计算所有星星的数量 let hasDecimal = score % 1 !== 0; // 非整数星星判断 let integer = Math.floor(score); // 整数星星判断 for (let i = 0; i < integer; i++) { // 整数星星使用on result.push(CLS_ON);// 一个整数星星就push一个CLS_ON到数组 } if (hasDecimal) { // 非整数星星使用half result.push(CLS_HALF);// 类似 } while (result.length < LENGTH) { // 余下的用无星星补全,使用off result.push(CLS_OFF);// 类似 } return result; } } });
HTML: 直接使用自定义的组件 prop-score 是传入的值,即点击后需要显示星星数量

<star-evaluation :prop-score="3.5" @click.stop="selectStar">star-evaluation>

你可能感兴趣的:(Vue.js 点击星星进行评价)