【Vue学习笔记_08】案例-图书购物车 (filters过滤器)

【Vue学习笔记_08】案例-图书购物车

  • 效果展示
  • filters
  • 代码
  • 技巧总结

这个案例结合了前面介绍的很多知识点,Mustache语法、v-if、v-else、v-for、v-bind、v-on、computed等等,以及新增知识点filters。

配套可执行代码示例 => GitHub

效果展示

【Vue学习笔记_08】案例-图书购物车 (filters过滤器)_第1张图片

filters

filters:过滤器,和methods、computed是并列的,有点像函数,接受参数并返回值,一般用于对数据进行一些格式转换或过滤处理操作。

filters使用格式:变量|过滤器

在下面这个例子中,过滤器showPrice实现把传入的totalPrice转换为¥格式并保留两位小数。

<h4>总价格:{{totalPrice | showPrice}}h4>
<script>
  const app = new Vue({
    el: '#app',
    filters: {
      showPrice(price) {
        return '¥' + price.toFixed(2)
      }
    },
    computed: {
      totalPrice() {
        ...
        return totalPrice
      }
    }
  })
script>

代码

index.html

<div id="app">
  <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="(book,index) in books">
        <td>{{book.id}}td>
        <td>{{book.name}}td>
        <td>{{book.date}}td>
        
        <td>{{book.price | showPrice}}td>
        <td><button @click="decrement(index)" v-bind:disabled="book.count <= 1">-button>{{book.count}}<button @click="increment(index)">+button>td>
        <td><button @click="removeHandle(index)">移除button>td>
      tr>
      tbody>
    table>
    <h4>总价格:{{totalPrice | showPrice}}h4>
  div>
  <h3 v-else>购物车为空h3>
div>

main.js

const app = new Vue({
  el: '#app',
  data: {
    books: [
      {
        id: 1,
        name: '算法导论',
        date: '2006-9',
        price: 85,
        count: 1
      },
      {
        id: 2,
        name: 'UNIX编程艺术',
        date: '2006-2',
        price: 59,
        count: 1
      },
      {
        id: 3,
        name: '编程珠玑',
        date: '2008-10',
        price: 39,
        count: 1
      }
    ]
  },
  methods: {
    getFinalPrice(price) {
      return '¥' + price.toFixed(2)
    },
    decrement(index) {
      this.books[index].count--
    },
    increment(index) {
      this.books[index].count++
    },
    removeHandle(index) {
      this.books.splice(index, 1)
    }
  },
  //过滤器
  filters: {
    showPrice(price) {
      return '¥' + price.toFixed(2)
    }
  },
  computed: {
    totalPrice() {
      //ES6数组遍历语法
      let totalPrice = 0
      for (let book of this.books) {
        totalPrice += book.price * book.count
      }
      return totalPrice
      //JS数组高阶函数
      return this.books.reduce(function (preValue, book) {
        return preValue + book.price * book.count
      }, 0)
    }
  }
})

计算totalPrice的时候使用了ES6数组遍历语法和JS数组高阶函数两种方式,更详细的介绍可以看这两篇笔记:

  • ES6常用语法总结
  • JavaScript数组高阶函数 (filter/map/reduce)

技巧总结

  1. v-if="books.length":当books数组为空时,不显示购物车table
  2. :v-for循环生成table的每一行
  3. :当一本书的count<=1时,减少按钮disabled,即不能再减少

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