Vue案例(购物车小案例)

在本次学习vue的过程中,涉及到了很多个组件同时还有每个组件中对应的属性,那么本次案例就是相对来说把vue中频繁用到的组件结合运用起来,以便熟能生巧,为以后的开发做好基础。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
      table {
    
    
          width: 500px;
          border: 1px solid #000;
          border-collapse: collapse;
          text-align: center;
      }

      th, tr, td {
    
    
          border: 1px solid #000;
      }
  </style>
</head>
<script type="text/javascript" src="/js/vue.global.js"></script>
<body>
<div id="app">
  <div v-if="books.length == 0">购物车为空</div>
  <div v-else>
    <table>
      <thead>
      <tr>
        <th>序号</th>
        <th>书名</th>
        <th>出版日期</th>
        <th>价钱</th>
        <th>数量</th>
        <th>操作</th>
      <tbody>
      <tr v-for="(book,index) in books">
        <td>{
    
    {
    
    index + 1}}</td>
        <td>{
    
    {
    
    book.name}}</td>
        <td>{
    
    {
    
    book.date}}</td>
        <td>{
    
    {
    
    book.price}}</td>
        <td>
          <button :disabled="book.index <= 1" v-on:click="sub(index)">-</button>&nbsp;
          //disabled作用就是当书籍小于1的时候禁用状态,不可以点击
          <span>{
    
    {
    
    book.count}}</span>&nbsp;
          <button v-on:click="add(index)">+</button>
        </td>
        <td>
          <button @click="del()">移除</button>
        </td>
      </tr>
      </tbody>
      </tr>
      </thead>
    </table>
    <br>
    总价钱:{
    
    {
    
    total}}
  </div>
</div>
</body>
</html>
<script>
  <!--    声明组合式api-->
  const {
    
    createApp, reactive, toRefs,computed} = Vue
  //  创建一个vue应用
  createApp({
    
    
    //    定义数据,方法等都写在setup函数中
    setup() {
    
    
      //定义的数据
      let count = 0;
      const data = reactive({
    
    
        books: [
          {
    
    name: '平凡的世界', date: '2010-12', price: 50, count: 1},
          {
    
    name: '红楼梦', date: '2010-12', price: 20.5, count: 1},
          {
    
    name: '水浒传', date: '2010-12', price: 100, count: 1},
          {
    
    name: '三国演绎', date: '2010-12', price: 150, count: 1},
        ], count
      })
      const del = (index) => {
    
    
        data.books.splice(index, 1)
      }
      //计算方法
      const total = computed(() => {
    
    
        let count = 0;
        for (const b of data.books) {
    
    
          count += b.price * b.count
        }
        return count;
      })
      const add = (i) => {
    
    
        data.books[i].count++
      }
      const sub = (i) => {
    
    
        data.books[i].count--
        if (data.books[i].count <= 1){
    
    
          data.books[i].count = 1;
        }
      }
      //定义的数据和方法都需要return返回
      return {
    
    ...toRefs(data), add, sub, del, total}
    }
  }).mount('#app')
</script>

运行结果:

猜你喜欢

转载自blog.csdn.net/weixin_52859229/article/details/130139216