实训第二天
继续进行vue的学习
简单学习一些基础语法:
computed (计算属性):
对一些data内的数据进行一些转化后进行显示。
可以由methods定义方法实现,但是使用computed进行计算的属性会被缓存,所以当多次调用该属性是,computed相比method会高效很多。
事件监听:与前端界面进行交互,
v-on: (语法糖@) 进行监听点击,拖拽,键盘事件等等
//监听鼠标:@click
// ./stop 阻止事件冒泡
<div @click="divBtn">
<button @click.stop="butBtn">按钮</button>
</div>
//监听键盘动作: @keyup
// .enter 特定监听回车键。enter可换成其他的键。
<input type="text" @keyup.enter="keyopo">
// .once 只触发一次回调
条件判断
v-if = boolean
v-elif = boolean
v-else
// v-if 与 v-show的 表现情况完全相同,bool为true 显示 为false不显示
// v-if bool为false 时,对应元素及其子元素不会被渲染
// v-show为false。只是将其display属性设置为none
//所以,当显示隐藏频繁用v-show 只有少数几次 用v-if
循环遍历
简单记一下参数: 分别是 (值 ,键, 下标)
<li v-for="(value,key,index) in info"> {{key}}-{{value}}-{{index}}</li>
总结案例:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
<table v-if="this.books.length!==0">
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(book,index) in books">
<th>{{index}}</th>
<th>{{book.name}}</th>
<th>{{book.data}}</th>
<th>{{book.price | showPrice}}</th>
<th>
<button @click="increment(index)">+</button>
{{book.num}}
<button @click="decrement(index)">-</button>
</th>
<th>
<button @click="del()">移除</button>
</th>
</tr>
<tr>
<th>总价:</th>
<th>${{totalPrice}}</th>
<!-- ${{totalPrice}}-->
</tr>
</tbody>
</table>
</div>
<script src="../js/vue.js"></script>
<script src="main.js"></script>
</body>
</html>
js
const app = new Vue({
el: '#app',
data: {
books: [
{name: '算法导论', 'data': 2006 - 9, 'price': 67.00, num: 1},
{name: 'Unix', 'data': 2006 - 2, 'price': 127.00, num: 1},
{name: 'OS', 'data': 2016 - 5, 'price': 34.00, num: 1},
{name: 'DS', 'data': 2003 - 3, 'price': 59.00, num: 1}
],
},
computed: {
// isShow(){
//
// },
totalPrice() {
total = 0
for (i = 0; i < this.books.length; i++) {
total += this.books[i].price * this.books[i].num
}
return total;
}
},
methods: {
increment(index) {
this.books[index].num++;
if (this.books[index].num < 0) {
this.books[index].num = 0;
}
},
decrement(index) {
this.books[index].num--;
if (this.books[index].num < 0) {
this.books[index].num = 0;
}
},
del(index){
this.books.pop(this.books[index])
}
},
filters: {
showPrice(price){
return '$' + price.toFixed(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;
}