【Vue3】基础语法案例-购物车

时间:2024-11-12 08:03:09
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>购物车</title>
    <style>
        table {
            width: 600px;
            color: #8f8e8e;
            text-align: center;
            border-collapse: collapse;
        }

        table thead {
            background: #F5F5F5;
        }

        table tr {
            height: 30px;
            line-height: 30px;
            border: 1px solid #ececec;
        }
    </style>
</head>

<body>
    <div id="app">
        <table>
            <thead>
                <tr>
                    <td><input type="checkbox" v-model="data.selected" @change="selectAll" /></td>
                    <td>商品</td>
                    <td>单价</td>
                    <td>库存</td>
                    <td colspan="2">操作</td>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(value, index) in data.list">
                    <td>
                        <input type="checkbox" v-model="data.checkboxList" :value="value" @change="checkSelect" />
                    </td>
                    <td>{{ value.name }}</td>
                    <td>{{ value.price }}</td>
                    <td>{{ value.stock }}</td>
                    <td>
                        <button @click="sub(value)">-</button>
                        {{ value.number }}
                        <button @click="add(value)">+</button>
                    </td>
                    <td><button @click="del(index,value.id)">删除</button></td>
                </tr>
            </tbody>
            <tfoot>
                <tr>
                    <td>总价 {{ totalPrice() }}</td>
                </tr>
            </tfoot>
        </table>
    </div>

    <script type="module">
        import { createApp, reactive } from './vue.esm-browser.js'

        createApp({
            setup() {
                const data = reactive({
                    selected: false,
                    checkboxList: [],
                    list: [{
                        id: 1,
                        name: "电脑",
                        price: 7000,
                        number: 1,
                        stock: 3
                    },
                    {
                        id: 2,
                        name: "鼠标",
                        price: 20,
                        number: 2,
                        stock: 5
                    },
                    {
                        id: 3,
                        name: "键盘",
                        price: 300,
                        number: 1,
                        stock: 6
                    }],
                })

                //减
                const sub = (value) => {
                    value.number--

                    if (value.number <= 1) {
                        value.number = 1
                    }
                }

                //加
                const add = (value) => {
                    value.number++

                    if (value.number >= value.stock) {
                        value.number = value.stock
                    }
                }

                //删除
                const del = (index, id) => {
                    data.list.splice(index, 1) //splice(要删除元素的索引位置, 要删除的元素数量)

                    //filter 筛选符合条件的元素, 返回一个新的数组
                    let newArr = data.checkboxList.filter((value, index) => {
                        return value.id != id
                    })
                    data.checkboxList = newArr

                    checkSelect() //检查勾选状态
                }

                //总价
                const totalPrice = () => {
                    let total = 0
                    for (let i = 0; i < data.checkboxList.length; i++) {
                        total += data.checkboxList[i].price * data.checkboxList[i].number
                    }

                    return total
                }

                //全选/反选
                const selectAll = () => {
                    if (data.selected) { //true
                        data.checkboxList = data.list
                    } else { //false
                        data.checkboxList = []
                    }
                }

                //检查勾选状态
                const checkSelect = () => {
                    if (data.checkboxList.length != data.list.length || data.list.length == 0) {
                        data.selected = false
                    } else {
                        data.selected = true
                    }
                }

                return {
                    data,
                    sub,
                    add,
                    del,
                    totalPrice,
                    selectAll,
                    checkSelect
                }
            }
        }).mount("#app")
    </script>
</body>
</html>

上述程序运行结果如下所示:
在这里插入图片描述

下面是购物车优化版

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>购物车2.0</title>
    <style>
        table {
            width: 600px;
            color: #8f8e8e;
            text-align: center;
            border-collapse: collapse;
        }

        table thead {
            background: #F5F5F5;
        }

        table tr {
            height: 30px;
            line-height: 30px;
            border: 1px solid #ececec;
        }
    </style>
</head>

<body>
    <div id="app">
        <table>
            <thead>
                <tr>
                    <!-- <td><input type="checkbox" v-model="data.selected" @change="selectAll" /></td> -->
                    <td><input type="checkbox" v-model="data.selected" /></td>
                    <td>商品</td>
                    <td>单价</td>
                    <td>库存</td>
                    <td colspan="2">操作</td>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(value, index) in data.list">
                    <!-- 
                    <td><input type="checkbox" v-model="data.checkboxList" :value="value" @change="checkSelect" /></td> 
                    -->
                    <td><input type="checkbox" v-model="data.checkboxList" :value="value" /></td>
                    <td>{{ value.name }}</td>
                    <td>{{ value.price }}</td>
                    <td>{{ value.stock }}</td>
                    <td>
                        <button @click="sub(value)">-</button>
                        {{ value.number }}
                        <button @click="add(value)">+</button>
                    </td>
                    <td><button @click="del(index,value.id)">删除</button></td>
                </tr>
            </tbody>
            <tfoot>
                <tr>
                    <!-- <td>总价 {{ totalPrice() }}</td> -->
                    <td>总价 {{ totalPrice }}</td>
                </tr>
            </tfoot>
        </table>
    </div>

    <script type="module">
        import { createApp, reactive, watch, computed } from './vue.esm-browser.js'

        createApp({
            setup() {
                const data = reactive({
                    selected: false,
                    checkboxList: [],
                    list: [{
                        id: 1,
                        name: "电脑",
                        price: 7000,
                        number: 1,
                        stock: 3
                    },
                    {
                        id: 2,
                        name: "鼠标",
                        price: 20,
                        number: 2,
                        stock: 5
                    },
                    {
                        id: 3,
                        name: "键盘",
                        price: 300,
                        number: 1,
                        stock: 6
                    }],
                })

                //减
                const sub = (value) => {
                    value.number--

                    if (value.number <= 1) {
                        value.number = 1
                    }
                }

                //加
                const add = (value) => {
                    value.number++

                    if (value.number >= value.stock) {
                        value.number = value.stock
                    }
                }

                //删除
                const del = (index, id) => {
                    data.list.splice(index, 1) //splice(要删除元素的索引位置, 要删除的元素数量)

                    //filter 筛选符合条件的元素, 返回一个新的数组
                    let newArr = data.checkboxList.filter((value, index) => {
                        return value.id != id
                    })
                    data.checkboxList = newArr

                    //checkSelect() //检查勾选状态
                }

                /*
                //总价
                const totalPrice = () => {
                    let total = 0
                    for (let i = 0; i < data.checkboxList.length; i++) {
                        total += data.checkboxList[i].price * data.checkboxList[i].number
                    }

                    return total
                }
                */
                //计算属性-有缓存 [计算属性根据其依赖的响应式数据变化而重新计算]
                const totalPrice = computed(() => {
                    /*
                        reduce定义: 用于对数组中的所有元素进行迭代操作, 并将每次操作的结果累加到一个初始值上
                        reduce接收两个参数: 一个是累加器函数, 另一个是初始值
                        reduce: 将 data.checkboxList 数组中的每个 checkbox 对象的 price 和 number 属性进行相乘, 
                        并将结果累加到初始值 0 上, 最后返回累加的结果

                        total(累加器) 用于存储每次计算的结果, 初始值为 0
                        item(当前元素) 在每次迭代过程中, 当前元素的值会被传递给回调函数
                    */

                    return data.checkboxList.reduce((total, item) => total + item.price * item.number, 0)
                })

                /*
                //全选/反选
                const selectAll = () => {
                    if (data.selected) { //true
                        data.checkboxList = data.list
                    } else { //false
                        data.checkboxList = []
                    }
                }
                */
                //监听 data.selected
                let flag = true
                watch(() => data.selected, (newValue, oldValue) => {
                    //console.log("newValue:",newValue,"oldValue:",oldValue)

                    if (newValue) {
                        data.checkboxList = data.list
                    } else {
                        if (flag) {
                            data.checkboxList = []
                        }
                    }
                    //console.log(data.checkboxList)
                })                

                /*
                //检查勾选状态
                const checkSelect = () => {
                    if (data.checkboxList.length == data.list.length && data.list.length != 0) {
                        data.selected = true
                    } else {
                        data.selected = false
                    }
                }
                */
                //监听 data.checkboxList
                watch(() => data.checkboxList, (newValue, oldValue) => {
                    console.log("newValue:", newValue, "oldValue:", oldValue)
                    console.log(newValue.length)

                    if (newValue.length == data.list.length && data.list.length != 0) {
                        data.selected = true
                        flag = true
                    } else {
                        data.selected = false
                        flag = false
                    }
                })                

                return {
                    data,
                    sub,
                    add,
                    del,
                    totalPrice,
                    //selectAll,
                    //checkSelect
                }
            }
        }).mount("#app")
    </script>
</body>
</html>