Vue练习(一)
- v-model:用于在表单类元素上双向绑定数据,例如 在输入框上使用时,输入的内容会实时映射到绑定的数据上。
- v-for:
- 将一个数组遍历或枚举一个对象循环,它的表达 式需结合 in 来使用,类似 item in items 的形式。
- v-for 的表达式支持一个可选参数作为当前项的索引
- 除了数组外, 对象的属性也是可以遍历
- v-for 还可以迭代整数
练习内容:用Vue完成一个简易的购物车
生成结果:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="vue .js"></script>
</head>
<style>
td {
text-align: center;
}
table,
th,
td {
padding: 8px 16px;
border: 1px solid black;
}
table {
empty-cells: show;
border-collapse: collapse;
}
th {
height: 30px;
background-color: darkgray;
}
button {
background-color: white;
border: 1px solid black;
}
</style>
<body>
<div id="app">
商品名称:<input type="text" v-model="name">
商品数量:<input type="text" v-model="num">
商品价格:<input type="text" v-model="price">
<button @click="newAdd()">添加</button>
<table>
<tr>
<th></th>
<th>商品名称</th>
<th>商品价格</th>
<th>购买数量</th>
<th>是否移除</th>
</tr>
<tr v-for="(i,index) in shop">
<td>{{index+1}}</td>
<td>{{i.name}}</td>
<td>{{i.price}}</td>
<td>
<button @click="Click1(index)">-</button>
{{i.num}}
<button @click="Click2(index)">+</button>
</td>
<td>
<button @click="Remove(index)">移除</button>
</td>
</tr>
</table>
<div>总计:{{sum}}</div>
</div>
</body>
<script>
var app = new Vue({
el: "#app",
data: {
shop: [{
name: "小猪",
price: 50,
num: 1,
show: true
},
{
name: "小狗",
price: 50,
num: 1,
show: true
},
{
name: "小猫",
price: 50,
num: 1,
show: true
}
],
name: "",
price: "",
num: ""
},
methods: {
Click1: function (index) {
this.shop[index].num = this.shop[index].num - 1;
if (this.shop[index].num <= 0) {
this.shop[index].num = 0;
}
},
Click2: function (index) {
this.shop[index].num = this.shop[index].num + 1;
},
Remove: function (index) {
this.shop.splice(index, 1);
},
newAdd: function () {
this.shop.push({
name: this.name,
price: parseInt(this.price),
num: parseInt(this.num),
show: true
})
}
},
computed: {
sum: function () {
var s = 0;
//console.log(this.shop[0].show)
for (var i = 0; i < this.shop.length; i++) {
if (this.shop[i].show) {
s = s + (this.shop[i].price) * (this.shop[i].num);
}
}
return s;
}
}
})
</script>
</html>