09-vue中过滤器使用和书籍购物车案例

过滤器使用详情

购物车案例

html部分代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>书籍购物车案例</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
<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="(item,index) in books">
        <td>{
   
   {item.id}}</td>
        <td>{
   
   {item.name}}</td>
        <td>{
   
   {item.productDate}}</td>
        <!--        使用过滤器-->
        <td>{
   
   {item.price | showPrice }}</td>
        <td>
          <button @click="decrement(index)" :disabled="item.number<= 1">-</button>
          {
   
   {item.number}}
          <button @click="increment(index)">+</button>
        </td>
        <td>
          <button @click="removeBook(index)">移除</button>
        </td>
      </tr>
      </tbody>
    </table>
    <h2>总价格: {
   
   {totalPrice | showPrice}}</h2>
  </div>
  <div v-else>
    <h2>购物车为空</h2>
  </div>
</div>

</body>
<script src="../js/vue.js"></script>
<script src="main.js"></script>
</html>

main.js部分代码:

const app = new Vue({
    
    
  el: '#app',
  data: {
    
    
    books: [
      {
    
    id: 1, name: 'unix', productDate: '2006-9', price: 102, number: 1},
      {
    
    id: 2, name: 'linux', productDate: '2008-9', price: 152, number: 1},
      {
    
    id: 3, name: 'javaScript', productDate: '2011-9', price: 52, number: 1},
      {
    
    id: 4, name: 'java', productDate: '2001-9', price: 78, number: 1},
      {
    
    id: 5, name: 'c++', productDate: '2002-9', price: 62, number: 1},
    ]
  },
  methods: {
    
    
    getTotalPrice: function (price) {
    
    
      return '¥' + price.toFixed(2)
    },
    decrement: function (index) {
    
    
      this.books[index].number--
    },
    increment: function (index) {
    
    
      this.books[index].number++
    },
    removeBook: function (index) {
    
    
      this.books.splice(index, 1)
    }
  },
  // 过滤器
  filters: {
    
    
    showPrice(price) {
    
    
      return '¥' + price.toFixed(2)
    }
  },
  computed: {
    
    
    totalPrice() {
    
    
      let totalPrice = 0
      for (const book of this.books) {
    
    
        console.log(book)
        totalPrice += book.number * book.price
      }
      return totalPrice
    }
  }
})

style.css部分代码:

table {
    
    
  border: 1px solid #e9e9e9;
  border-collapse: collapse;
  border-spacing: 0;
}

th, td {
    
    
  padding: 8px 16px;
  border: 1px solid #e9e9e9;
  text-align: left;
}

th {
    
    
  background-color: #f7f7f7;
  color: #5c6b77;
  font-weight: 600;
}

猜你喜欢

转载自blog.csdn.net/plan_jok/article/details/112989406
今日推荐