2.遍历数组

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <!-- 开发环境版本,包含了有帮助的命令行警告 -->
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <!--<script src="./js/vue.js"></script>-->
</head>
<body>
<div id="app">
  <h3>{{title}}</h3>
  <h4>1.遍历数组</h4>
  <h4>订单列表如下(不取下标)</h4>
  <ul>
    <li v-for="item in orderList">
      {{item.orderName}}---- {{item.price}}---- {{item.num}}
    </li>
  </ul>
  <h4>合计:{{allPrice}}</h4>

  <h4>订单列表如下(取下标)</h4>
  <ul>
    <li v-for="(item,index) in orderList">
      {{index+1}}. {{item.orderName}}---- {{item.price}}---- {{item.num}}
    </li>
  </ul>
  <h4>合计:{{allPrice}}</h4>
</div>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      title: '循环遍历v-for简单使用',
      name: 'ldp',
      orderList: [
        {orderName: '方便面', price: 3, num: 6},
        {orderName: '鸡腿', price: 8, num: 1},
        {orderName: '手机', price: 39, num: 4},
        {orderName: '', price: 12, num: 9}
      ]
    },
    computed: {
      allPrice: function () {
        // 高阶函数 all表示每次的结果,item表示循环出来的每个对称 , reduce 函数的第二个参数表示 all=0开始累加
        return this.orderList.reduce((all, item) => {
          return all + item.price * item.num
        }, 0)
      }
    }
  });
</script>
</body>
</html>
View Code

相关文章: