vue基础语法

本文主要介绍Vue的基础语法,通过购物车案例演示v-指令的使用。同时,对比了计算属性computed与方法methods的区别:计算属性在数据不变时只计算一次,有缓存;而方法每次调用都会执行。

vue基础语法<二>

利用v-标签实现小案例
购物车案例:

<style>
    table {
      border-collapse: collapse;
    }
    td, th {
      border: 1px solid #c7c2c2;
    }
  </style>
</head>
<body>
<div id="shop-cart">
  <div v-if="books.length">
  <table>
    <thead>
    <tr>
      <th></th>
      <th>书籍名称</th>
      <th>出版日期</th>
      <th>价格</th>
      <th>购买数量</th>
      <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr v-for="(item, index) in books" :key="item">
      <td>{{index+1}}</td>
      <td>{{item.name}}</td>
      <td>{{item.date}}</td>
      <td>{{item.price | finalPrice}}</td>
      <td>
<!--        当书本数量为1时,按钮不可以在减,则当number<=1 时,动态绑定属性disabled   -->
        <button @click="decrement(index)" :disabled="item.number <= 1">-</button>
        {{item.number}}
        <button @click="increment(index)">+</button>
      </td>
      <td>
        <button @click="move(index)">移除</button>
      </td>
    </tr>
    </tbody>
  </table>
  <h2>总的价格:{{totalPrice | finalPrice}}</h2>
  </div>
  <div v-else><h2>购物车为空</h2></div>
</div>

<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#shop-cart',
    data: {
      books: [
        {name: '《算法导论》', date: '2006-9', price: 85.00, number:1},
        {name: '《UNIX编程艺术》', date: '2006-2', price: 59.00, number:1},
        {name: '《编程珠玑》', date: '2008-10', price: 89.00,  number:1},
        {name: '《代码大全》', date: '2006-3', price: 128.00,  number:1}
      ],
    },
    computed: {     //计算属性
      totalPrice() {
        // let result = 0;
        // for (let book of this.books) {
        //   result += book.price * book.number;
        // }
        // return result;
        return this.books.reduce(function(preValue, book){
          return preValue + book.price * book.number;
        },0);
      }
    },
    methods: {
      increment(index) {
        this.books[index].number++;
      },
      decrement(index) {
        this.books[index].number--;
      },
      move(index) {
        this.books.splice(index, 1); //移出index位置的书本
      },
    },
    filters: {     //过滤器
      finalPrice(price) {
        return '¥' + price.toFixed(2); //使数字以两位小数表示
      }
    }
  })
</script>
</body>

注意计算属性computed与方法methods的区别:
当数据不变时,计算属性中的函数只计算一遍,只有当数据变化时再重新计算,有缓存
而methods中的函数是每调用一次就运行一次

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值