逛水果店案例

128 阅读1分钟

逛水果店

  • 本店收银系统采用vue开发,冲这点,你不来买点试试?
  • 提示: v-model="变量" 输入框的值会绑定给vue的这个变量(别忘了在data里先声明)
  1. 将固定的数据渲染成动态数据
  2. 输入框 v-model获取数据 count count购买几斤
  3. 按钮添加点击事件
  4. 当按钮点击时 this.allPrice = this.price * this.count
  5. 相当于 总价 = 苹果的单价 * 输入的个数

代码解释: HTML中的一个表格单元格元素(td),其中包含一个文本输入框(input), 用于输入要购买的商品数量的斤数。这个输入框的值会通过Vue.js中的v-model指令绑定 到组件的data对象中的count属性上,可以在Vue.js组件实例中访问和操作这个count属性 的值。同时,这个输入框还有一个占位符(placeholder)文本,用于在输入框为空时显示 提示信息。

<!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>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>

</head>
<body>
  <div id="app">
    <table width=800 style="text-align: center; margin: 0 auto;" border=1>
      <caption>欢迎光临_vue开发的收银系统_水果店</caption>
      <tr>
        <th>苹果 {{ price }} ¥ / 斤, 折扣 &lt; {{ dis * 10 }} 折 &gt;</th>
      </tr>
      <tr>
        <td>
          请输入你要购买的斤数 <input type="number" v-model="count"  placeholder="斤数">
        </td>
      </tr>
      <tr>
        <td>
          <!-- 静态页面6个变量使用后, 绑定点击事件 -->
          <button @click="buy">结账买单~</button>
        </td>
      </tr>
      <tr>
        <td>
          结账单:
          <span>总价: {{ allPrice }} ¥元</span>
          <span>折后价: {{ disPrice }} ¥元</span>
          <span>省了: {{ savePrice }} ¥元</span>
        </td>
      </tr>
    </table>
  </div>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        price: 10, // 苹果单价
        dis: 0.8, // 折扣
        count: 0, // 购买的斤数
        allPrice: 0, // 总价
        disPrice: 0, // 折后价格
        savePrice: 0, // 省了多少钱
      },
      methods: {
        buy(){
          // 把 count 保存的数量和单价和折扣等计算
          this.allPrice = this.price * this.count
          this.disPrice = this.allPrice * this.dis
          this.savePrice = this.allPrice - this.disPrice
        }
      }
    })
  </script>
</body>
</html>