javascript - 使用 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')
这有效,但仅在页面加载时有效,但我尝试在选择数量更改时更改总数。
我有点迷失了实现这一目标,我应该使用手表但是在什么上?还是别的什么?
解决方案
最后我找到了如何实现这一点,问题是我的数组不在 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')
推荐阅读
- javascript - 为什么一个包的依赖会影响另一个包
- android - 无法在 MPChartView android 上的 xAxis 上设置标签
- java - 如何使用 Gson 删除 Json 对象的嵌套字段
- java - 相同的小数,不同的舍入结果?
- ubuntu - 无法弄清楚 VirtualBox(Ubuntu) 的问题
- windows-10 - Python Asyncio:RuntimeEror:此事件循环已在运行
- java - 在Java中反向输出数组的内容
- c# - 如何根据实体框架中的下拉列表选定项填充表单字段以进行更新?
- reactjs - 除非 notifyOnNetworkStatusChange 设置为 true,否则 react-apollo 重新获取不起作用?
- c# - 无法保存使用 ASP.NET C# Web 窗体接收的 Razorpay Webhook 数据