购物车案例

HTML

    <template id="my-app">
        <table>
            <thead>
                <th>序号</th>
                <th>书籍名称</th>
                <th>出版时间</th>
                <th>价格</th>
                <th>购买数量</th>
                <th>操作</th>
            </thead>
            <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.count <= 1" @click="decrement(index)">-</button>
                        {{book.count}}
                        <button @click="increment(index)">+</button>
                    </td>
                        
                    <td>
                        <button @click="removeBook(index)">移除</button>
                    </td>
                </tr>
            </tbody>

        </table>
        <h2>总价格:{{totelPrice}}$</h2>
    </template>

js

Vue.createApp({
    template: "#my-app",
    data() {
        return {
            books: [{
                    id: 1,
                    name: '《算法导论》',
                    price: 12,
                    date: '2022-6',
                    count: 1
                },
                {
                    id: 2,
                    name: '《java》',
                    price: 11,
                    date: '2012-6',
                    count: 1
                },
                {
                    id: 3,
                    name: '《javasCript》',
                    price: 14,
                    date: '2022-4',
                    count: 2
                },
                {
                    id: 4,
                    name: '《数据库》',
                    price: 16,
                    date: '2022-1',
                    count: 3
                },
                {
                    id: 5,
                    name: '《系统设计与实现》',
                    price: 55,
                    date: '2020-6',
                    count: 1
                }
            ]
        }
    },
    computed: {
        totelPrice() {
            let finalprice = 0
            for (let book of this.books) {
                finalprice += book.price * book.count
            }
            return finalprice
        }
    },
    methods: {
        increment(index) {
            this.books[index].count++
        },
        decrement(index) {
            this.books[index].count--
        },
        removeBook(index) {
            this.books.splice(index, 1)
        }
    }
}).mount("#app")

posted @ 2022-05-24 12:28  xuelin  阅读(30)  评论(0编辑  收藏  举报