Vue.jsにてレビューの星を実装する
- CREATE:2022-07-14
- UPDATE:2022-07-14
概要
Vue.jsにてレビューの星を実装します。
今回は、CDNにて実装します。
つまりどういうこと?
クリックすれば、星の光の数が変わります。
仕組み
v-bind:classとcomputedにて、星の数を決めるDataのStarの数値に応じたClassを付与するといった形です。
ソースコード
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/style.css" />
<title>Document</title>
</head>
<body>
<div id="app">
<div id="stars">
<span id="star" @click="review(1)" v-bind:class="color">★</span>
<span id="star" @click="review(2)" v-bind:class="color">★</span>
<span id="star" @click="review(3)" v-bind:class="color">★</span>
<span id="star" @click="review(4)" v-bind:class="color">★</span>
<span id="star" @click="review(5)" v-bind:class="color">★</span>
</div>
</div>
<!-- 開発バージョン、便利なコンソールの警告が含まれています -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="javascript/javascript.js"></script>
</body>
</html>
/style/style.css
#star
{
font-size: 32px;
}
/* 何故か効かない。単に知識不足か記述ミスか? */
.star1::nth-child(-n+1),
.star2::nth-child(-n+2),
.star3::nth-child(-n+3),
.star4::nth-child(-n+4),
.star5 {
color:yellow;
}
/* これで効きました */
.star1:first-child
{
color:yellow;
}
//(n+X)の場合、Xから最後まで
//(-n+X)の場合、1からXまで
.star2:nth-child(-n+2)
{
color:yellow;
}
.star3:nth-child(-n+3)
{
color:yellow;
}
.star4:nth-child(-n+4)
{
color:yellow;
}
.star5
{
color:yellow;
}
/javascript/javascript.js
var app = new Vue({
el: "#app",
data: {
star: 0,
},
methods: {
review: function (value) {
this.star = value;
},
},
computed: {
color: function () {
if (this.star === 5) {
return "star5";
} else if (this.star === 4) {
return "star4";
} else if (this.star === 3) {
return "star3";
} else if (this.star === 2) {
return "star2";
} else if (this.star === 1) {
return "star1";
} else {
return "star0";
}
},
},
});