vue图书小案例

2023-06-12,,

小知识点:

vue中计算属性有缓存(对象属性变化时才会更新),方法没有缓存,所以计算属性比方法效率高
js中let有块级作用域,var没有块级作用域,所以var是有缺陷的
this.letters[0] = 'bb'; //vue中,这种做法并不是响应式的;推荐使用响应式方法:this.letters.splice(0,1,'cc');

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<body>
<div id="app">
<ul v-if="books.length">
<ul>
<li v-for="(v,k) in books">
<button @click="add(k,false)" :disabled="v.num <= 1">-</button>
<input type="text" :value="v.num">
<button @click="add(k,true)">+</button> <div>{{v.name}}</div>
<div>{{v.price * v.num | showPrice}}</div> <button @click="rm(k)">移除</button>
</li>
</ul>
总价{{total_price | showPrice}}
</ul> <div v-else>当前没有图书</div>
</div>
</body>
<script>
let v = new Vue({
el : "#app",
data : {
books : [
{
name : '天龙八部',
price : 33,
num : 1,
},
{
name : '鹿鼎记',
price : 13,
num : 1,
},
]
},
methods : {
add : function(k,boo){
let obj = this.books[k];
if(boo) {
obj.num+=1;
}else{
obj.num-=1;
}
//this.books.splice(k,k+1,obj);
},
rm : function(k){
this.books.splice(k,1);
}
},
// 计算属性
computed : {
total_price : function(){
let total = 0;
for(let i = 0;i < this.books.length;i++ ){
total += (this.books[i].price * this.books[i].num);
}
return total;
}
},
// 过滤器
filters : {
showPrice : function(price){
return '$' + price.toFixed(2);
}
}
})
</script>
</html>

vue图书小案例的相关教程结束。

《vue图书小案例.doc》

下载本文的Word格式文档,以方便收藏与打印。