首页 > 解决方案 > 使用 Vue 3 观看选择数量选择器

问题描述

我正在尝试使用现有项目制作一个快速购物车。

我的列表项已经由 php 生成,我可以使用这样的 html 元素:

const billets = document.querySelectorAll(".card-billet");

var products = [];

billets.forEach(billet => {
    products.push({
        title: billet.querySelector('.card-billet-title').textContent,
        price: billet.dataset.price,
        qty: billet.querySelector('select[name="billet_quantity"]').value
    });
});

const App = {
    data() {
        return {
            items: products
        }
    },
    watch: {
        items: function () {
            console.log("watched");
        },
    },
    computed: {
        total: function () {
            console.log(this.items)

            let total = 0.00;
            this.items.forEach(item => {
                total += (item.price * item.qty);
            });
            return total;
        }
    }
}

Vue.createApp(App).mount('#checkoutApp')

这有效,但仅在页面加载时有效,但我尝试在选择数量更改时更改总数。

我有点迷失了实现这一目标,我应该使用手表但是在什么上?还是别的什么?

标签: javascriptvuejs3shopping-cart

解决方案


最后我找到了如何实现这一点,问题是我的数组不在 vue 实例中,所以无法更新。

我简化了这样的代码:

const App = {
    data() {
        return {
            items: []
        }
    },
    methods: {
        onChange: function (e) {
            // console.log(this.items)
            this.items = [];

            document.querySelectorAll(".card-billet").forEach(billet => {
                this.items.push({
                    title: billet.querySelector('.card-billet-title').textContent,
                    price: billet.dataset.price,
                    qty: billet.querySelector('.card-billet-qty-selector').value
                });
            });
        }
    },
    computed: {
        total: function () {
            // console.log(this.items)

            let total = 0.00;
            this.items.forEach(item => {
                total += (item.price * item.qty);
            });
            return total;
        }
    }
}

Vue.createApp(App).mount('#checkoutApp')

推荐阅读