主要功能
點(diǎn)擊某一項(xiàng)的時候其變?yōu)辄S色,然后自動計算所有變?yōu)辄S色項(xiàng)目的數(shù)字之和脉幢。
學(xué)習(xí)到的知識點(diǎn)
v-on綁定click事件來改變data屬性中的某一項(xiàng)
v-bind動態(tài)為元素添加class=‘a(chǎn)ctive’屬性
v-for循環(huán)插入元素
難點(diǎn)
大括號嵌套多了歪沃,容易糊涂 。
注意forEach遍歷的用法嫌松。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
</head>
<style>
*{
margin:0;
padding:0;
}
div {
width:400px;
background: pink;
margin:50px auto; /* make it in the center*/
padding:40px 80px;/* 40 means top and bottom ,while 80 means left and right*/
}
body{
font-family:Microsoft YaHei;
}
span {
float:right;
}
ul {
font-size:40px;
}
li {
list-style-type: none;
}
ul li {
margin-top:5px;
margin-right:35px;
background:palegreen;
}
ul li.active{
background-color:yellow;
}
p {
font-size:40px;
margin:10px 35px;
background: pink;
}
</style>
<div id="main" v-cloak>
<ul>
<li v-for="item in items" v-on:click="toggleActive(item)" v-bind:class="{'active':item.active}">
<!--v-bind的意思是說如果item.active是true沪曙,那么li就有<class="active">這個屬性,否則就沒有萎羔。這個是根據(jù)data中的
值來決定的液走。
v-on 依據(jù)點(diǎn)擊,點(diǎn)擊了就調(diào)用toggleActive(item)函數(shù)外驱,這個函數(shù)改變active的屬性育灸,如果active是false腻窒,
就改成true昵宇,如果是true,就改成false儿子。
-->
{{item.name}}<span>{{item.price}}</span></li>
</ul>
<p>Total:<span>{{total()}}</span></p>
</div>
<script>
var demo=new Vue({
el:'#main',
data:{
items:[{
name:'baicai',
price:200,
active:true,
},
{
name:'doujiao',
price:300,
active:false,
},
{name:'tudou',
price:220,
active:false,}]
},//, is necessary
methods:{
toggleActive: function(i){
i.active = !i.active;
},
// change active value瓦哎, i是形參。
total:function(){
var total=0;
this.items.forEach(function(s){
if (s.active){
total+=s.price;
}
})//forEach over at here
return total;
}//total over at here
}//methods over at here
})//vue over at here
</script>
實(shí)現(xiàn)簡單的計算功能。