小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
本文已参与「掘力星计划」,赢取创作大礼包,挑战创作激励金。
用框架写程序经常用到的组件库中, 都会有 五星评价小组件, 组件库--之为库 就是一个个组件的库, 所以我们会写组件, 在加上工程化的东西进行构思也能写出自己的组件库, 可能并不是那个完美, 但是都可以尝试的.
Vue 必备小知识: 五星评价 的两种实现方案
实现效果:
方法一: 普通 div
:class="{'active': curindex>=n}"就是利用判断条件 curIndex >= n, 如果为真, 就为 标签加上类名: .active.
<head>
<script src="js/vue.js"></script>
<style>
.box div {
background: url('img/off.png');
width: 56px;
height: 59px;
float: left;
}
.box .active {
background: url('img/on.png');
}
</style>
</head>
<body>
<div id="box" class="box">
<div
v-for="n in 5"
@mouseenter="enter(n)"
@mouseleave="out"
@click="ok(n)"
:class="{'active':curIndex>=n}"
></div>
</div>
<script>
new Vue({
el: '#box',
data: {
curIndex: 0, // 保存的当前鼠标经过的项目的序号
flag: false, // false 表示鼠标没有点击过,true,表示选择过
},
methods: {
enter(n) {
//n 取值1-5
if (!this.flag) {
this.curIndex = n
}
},
out() {
if (!this.flag) {
// 没有点击过,curIndex值才会变化
this.curIndex = -1
}
},
},
})
</script>
</body>
方法二: 组件化的方法
注意: 组件上的 事件不会执行, 需要加上 .native 修饰符,
<head>
<script src="js/vue.js"></script>
<style>
.box div {
background: url('img/off.png');
width: 56px;
height: 59px;
float: left;
}
.box .active {
background: url('img/on.png');
}
</style>
</head>
<body>
<div id="box" class="box">
<star
v-for="n in 5"
@mouseenter.native="enter(n)"
@mouseleave.native="out"
@click.native="ok(n)"
:class="{'active':curIndex>=n}"
:title="n"
>
</star>
</div>
<script>
var star = {
template: '<div></div>',
}
new Vue({
el: '#box',
components: {
star,
},
data: {
curIndex: 0, // 保存的当前鼠标经过的项目的序号
flag: false, // false 表示鼠标没有点击过,true,表示选择过
},
methods: {
enter(n) {
//n 取值1-5
if (!this.flag) {
this.curIndex = n
}
},
out() {
if (!this.flag) {
// 没有点击过,curIndex值才会变化
this.curIndex = 0
}
},
ok(n) {
this.flag = true
this.curIndex = n // 确认评价的星级数
},
},
})
</script>
</body>