Vue3案例——使用监听器设计购物车效果

Vue3案例——使用监听器设计购物车效果

本节将使用监听器设计购物车效果,这个购物车需要满足以下需求:

(1)当用户每次修改预购买商品的名称的时候,都需要清空购买数量。

(2)对购物车数据进行侦听,每次单击“加入购物车”按钮,会显示商品名称和数量。

【例5.18】  设计购物车效果(源代码\ch05\5.18.html)。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用监听器设计购物车效果</title>
</head>
<body>

<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@3/dist/vue.global.js"></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>

</body>
</html>

在Chrome浏览器中运行程序,输入商品名称后多次单击“加一个”按钮,然后单击“加入购物车”按钮,结果如图5-25所示。

本文节选自《Vue.js 3.x+Element Plus从入门到精通(视频教学版)》,获出版社和作者授权发布。

  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值