一、案例一:v-for+v-bind+v-on
- 案例描述
定义一个数组books: ['数据结构‘,‘计算机网络’,‘算法设计与分析’,‘计算机组成原理’]
将列表显示在网页中,并在点击其中一本书时,显示蓝色
- 代码分析
<style>
.active{
color:blue;
}
</style>
<div id="hey">
<ul>
<li v-for="(item,index) in books"
:class="{active: currentIndex == index}"
@click="liClick(index)">
{{index}}.{{item}}
</li>
</ul>
</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#hey',
data: {
books:['数据结构','计算机网络','算法设计与分析','计算机组成原理'],
currentIndex:0
},
methods:{
liClick(index){
this.currentIndex = index
}
}
})
</script>
二、案例二:花店购物车
- 案例描述
实现如下页面
其中 某种花的数量+1,总价格要相应增加;
点击"移除"按钮时,删除那一列的花
*代码分析
1.html
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>花店购物车</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
<div v-if="flowers.length">
<table>
<!--头是写死的-->
<thead>
<tr>
<th></th>
<th>花的名字</th>
<th>花的种类</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in flowers">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.type}}</td>
<td>{{item.price | showPrice}}</td>
<td>
<button @click="decrement(index)" v-bind:disabled="item.count <= 1">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td><button @click="removeHandle(index)">移除</button></td>
</tr>
</tbody>
</table>
<h2>总价格:{{totalPrice | showPrice}}</h2>
</div>
<h2 v-else>购物车为空</h2>
</div>
<script src="vue.js"></script>
<script src="main.js"></script>
</body>
</html>
2.css
table{
border:1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
}
th,td{
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: left;
}
th{
background-color: #f7f7f7;
color:#5c6b77;
font-weight: 600;
}
3.javascript
const app = new Vue({
el: '#app',
data: {
flowers:[
{
id:1,
name:'心语',
type:'满天星',
price:60.00,
count:1
},
{
id:2,
name:'骄阳',
type:'牡丹花',
price:100.00,
count:1
},
{
id:3,
name:'烟遇',
type:'玫瑰',
price:99.00,
count:1
},
{
id:4,
name:'Thanksgodness',
type:'康乃馨',
price:80.00,
count:1
}
]
},
methods:{
increment(index){
this.flowers[index].count++
},
decrement(index) {
this.flowers[index].count--
},
removeHandle(index){
this.flowers.splice(index,1)
}
},
computed:{
totalPrice(){
let totalPrice = 0;
for(let i=0;i<this.flowers.length;i++){
totalPrice += this.flowers[i].price * this.flowers[i].count
}
return totalPrice
}
},
filters:{
showPrice(price){
return '¥' + price.toFixed(2)
}
}
})