本节将使用监听器设计购物车效果,这个购物车需要满足以下需求:
(1 )当用户每次修改预购买商品名称的时候,都需要清空购买数量。
(2 )对购物车数据进行侦听,每次单击“加入购物车”按钮,会显示商品名称和数量。
【例7.5 】设计购物车效果(源代码\ch07\7.5.html )。
<div id="app">
<div>商品名称:<input v-model="name"/></div>
<button v-on:click="cut">减一个</button>
购买数量{{count}}
<button v-on:click="add">加一个</button>
<button v-on:click="addCart">加入购物车</button>
<div v-for="(item, index) in list" :key="index">
{{item.name}} x{{item.count}}
</div>
</div>
<!--引入vue文件-->
<script src="https://unpkg.com/vue@next"></script>
<script>
//创建一个应用程序实例
const vm= Vue.createApp({
//该函数返回数据对象
data(){
return{
name: '',
count:0,
isMax: false,
list: []
}
},
methods: {
cut() {
this.count = this.count - 1
this.isMax = false
},
add() {
this.count = this.count + 1
},
addCart() {
this.list.push({
name: this.name,
count: this.count
})
}
},
watch: {
count: function(newVal, oldVal) {
if(newVal > 10) {
this.isMax = true
}
if(newVal < 0) {
this.count = 0
}
},
name: function() {
this.count = 0,
this.isMax = false
}
}
//在指定的DOM元素上装载应用程序实例的根组件
}).mount('#app');
</script>
在Chrome 浏览器中运行程序,输入商品名称后多次单击“加一个”按钮,然后单击“加入购物车”按钮,结果如图7-8 所示。


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/18841117/viewspace-2966310/ ,如需转载,请注明出处,否则将追究法律责任。