简单vue综合实例

本文通过一个购物车应用实例介绍了 Vue.js 的基本用法。包括如何使用 v-if 控制元素显示隐藏、v-for 循环遍历数据、@click 绑定点击事件以及自定义方法实现数据更新等。通过此示例可以快速上手 Vue.js 并理解其响应式原理。
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/vue.js" ></script>
		<style type="text/css">
			
			table{
				width: 600px;
				border-collapse: collapse;
				font-family: "楷体";
			}
			td,th{
				border: 1px solid #ccc;
				text-align: center;
				padding: 5px;
			}
			tr:nth-child(even){
				background-color: #f5f5f5;
			}
			
		</style>
	</head>
	<body>
		<!--
			vue的入门:、
			(1)页面引入一个js   vue.js  vue.min.js
			(2)要有一个挂载的标签  给它设定id(通常是id)或者class
			(3)使用js代码实例化一个Vue对象
				3.1 设置挂载的标签  -- el
				3.2 绑定的数据  data:{}
				3.3 绑定的方法 methods:{}
			(4)在标签中使用绑定的数据,或者调用绑定的方法
				{{mesage}}
				@click="clickMe"
			-->
		<div id="app">
			
			<table v-if="products.length>0">
				<thead>
					<tr>
						<th>编号</th>
						
						<th>名称</th>
						
						<th>单价</th>
						
						<th>数量</th>
						
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
					<tr v-for="(product,index) in products">
						<td>{{product.id}}</td>
						
						<td>{{product.name}}</td>
						
						<td>{{product.price}}</td>
						
						<td>
							<button @click="decrease(index)" :disabled="product.count==1">-</button>
							{{product.count}} 
							<button @click="increase(index)">+</button>
						</td>
						
						<td><button @click="removeProduct(index)">删除</button></td>
					</tr>
				</tbody>
				<tfoot>
					<tr>
						<td colspan="5">
							总金额:{{sumMoney()}}
						</td>
					</tr>
				</tfoot>
			</table>
			
			<div v-else>暂无数据......</div>
			
		</div>
		
		<script>
			
			var vm = new Vue({
				
				el:"#app",
				
				data:{
					products:[
						{
							id:1,
							name:"锤子",
							price:10.00,
							count:1
						},
						{
							id:2,
							name:"毛线",
							price:20.00,
							count:2
						},
						{
							id:3,
							name:"铲铲",
							price:15.00,
							count:1
						}
					]
				},
				
				methods:{
					
					increase(index){
						let product = this.products[index];
						product.count++;
					},
					decrease(index){
						let product = this.products[index];
						if(product.count==1){
							return;
						}
						product.count--;
					},
					removeProduct(index){
						//删除数据中products数组的某个元素
						this.products.splice(index,1);
					},
					//求总金额
					sumMoney(){
						let total = 0;
						for (let i in this.products) {
							total+=this.products[i].price*this.products[i].count;
						}
						return total;
					}
					
				}
				
			})
			
			
			
		</script>
		
	</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值