Vue computed计算属性购物车实例

效果演示

对于computed的计算属性可以通过这个购物车例子来了解,笔者最近很是疲累,真的不想过多解释了,还请读者自行看代码研究。
Vue computed计算属性购物车实例_第1张图片

参考代码

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
  <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.10/vue.js">script>
  <style>
    .container {
      width: 80%;
      margin: 30px auto;
    }

    table {
      width: 100%;
      border: 1px solid blue;
      border-collapse: collapse;
    }

    th {
      height: 50px;
    }

    td{
      height: 32px;
    }

    th, td {
      border-bottom: 1px solid blue;
      text-align: center;
    }
  style>
head>
<body>
<div id="app">
  <div class="container">
    <table>
      <tr>
        <th>序号th>
        <th>商品名称th>
        <th>商品价格th>
        <th>购买数量th>
        <th>操作th>
      tr>
      <tr v-for="iphone in goods">
        <td>{{ iphone.id }}td>
        <td>{{ iphone.name }}td>
        <td>{{ iphone.price }}td>
        <td>
          <button v-bind:disabled="iphone.count === 0" v-on:click="iphone.count-=1">-button>
          {{ iphone.count }}
          <button v-on:click="iphone.count+=1">+button>
        td>
        <td>
          <button v-on:click="iphone.count=0">移除button>
        td>
      tr>
    table>
    <p style="text-align:right;"> 总价:${{totalPrice}}p>

  div>
div>
<script>
  var app = new Vue({
    el: '#app',
    data: {
      goods: [{
        id: 1,
        name: 'iphone 15 128g',
        price: 5999,
        count: 1
      },
        {
          id: 2,
          name: 'iphone 15 plus 128g',
          price: 6999,
          count: 1
        },
        {
          id: 3,
          name: 'iphone 15 pro 256g',
          price: 8999,
          count: 1
        }]

    },
    computed: {
      totalPrice: function () {
        var totalP = 0;
        for (var i = 0, len = this.goods.length; i < len; i++) {
          totalP += this.goods[i].price * this.goods[i].count;
        }
        return totalP;
      }
    }
  })
script>
body>
html>

你可能感兴趣的:(vue.js,vue.js,前端,javascript)