vue 学习笔记
响应式
并不是所有方法都是响应式,pop(),shift(),unshift(),splice(),sort(),reverse()是响应式的
shift():删除数组的最前面一个元素
unshift():在数组最前面添加元素
splice():可以删除元素,插入元素,替换元素
删除元素:第二个参数传入你要删除几个元素(如果没有传,就删除后面的所有元素)
替换元素:第二个参数,表示我们要替换几个元素,后面是用于替换前面的元素。
插入元素,第二个参数传入0,后面跟上要插入的元素
通过索引来修改数组的元素不是响应式的
Vue.set()
vue.set(要修改的对象,索引值,修改后的值)
购物车案例
实现:如图所示
代码:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
<div v-if = "books.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 books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<!-- <td>{{getFinalPrice(item.price)}}</td> -->
<!-- 过滤器方法 -->
<td>{{item.price | showPrice}}</td>
<td>
<!-- disable表示按钮不能按 -->
<button @click = "decrement(index)" v-bind:disabled="item.count <= 1" >-</button>
{{item.count}}
<button @click = "increment(index)">+</button>
</td>
<td><button @click="removeHandle">移除</button></td>
</tr>
</tbody>
<h3>总价格:{{totalPrice | showPrice}}</h3>
</table>
</div>
<h2 v-else="购物车为空"></h2>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="main.js"></script>
</body>
</html>
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;
}
js:
const app = new Vue({
el:"#app",
data:{
books:[
{
id:1,
name:'AABB',
date:'2020-1',
price:10.00,
count:1
},
{
id:2,
name:'CCDD',
date:'2020-2',
price:12.00,
count:1
},
{
id:3,
name:'MMNN',
date:'2020-3',
price:19.00,
count:1
},
{
id:4,
name:'OOPP',
date:'2020-4',
price:88.00,
count:1
}
]
},
methods:{
//将价格保留两位小数 并加上¥这个符号
getFinalPrice(price){
return '¥'+price.toFixed(2);
},
increment(index){
this.books[index].count++;
},
decrement(index){
this.books[index].count--;
},
removeHandle(index){
this.books.splice(index,1);
}
},
computed:{
//总价格用计算属性
totalPrice(){
let totalPrice=0;
for(let i=0;i<this.books.length;i++){
totalPrice +=this.books[i].price * this.books[i].count;
}
//忘记返回值了
return totalPrice;
}
},
//过滤器
filters:{
showPrice(price){
return '¥'+ price.toFixed(2);
}
}
})