laravel - 不知道如何在vue中一次性节省价格
问题描述
我有一张表格,列出了我所有的产品及其价格,我将价格作为输入,我想做的是,当我点击保存时,我需要能够保存我一次更改的所有价格时间。
我不知道该怎么做。
这是我的代码
<template>
<div>
<table class="table table-sm table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="product in products">
<td>{{product.name}}</td>
<td>
<input @change="onChange(product)" v-model="product.prices">
</td>
</tr>
</tbody>
</table>
<div>
<div class="btn btn-success" @click="updatePrices()">
Save Prices
</div>
</div>
</template>
<script>
export default {
props: ['products'],
data() {
return {
product: {
price: null
}
}
},
methods: {
updatePrices(){
console.log(this.products.price);
}
},
mounted(){
}
}
</script>
解决方案
您的问题是关于数据传递的两个部分。
- 从 Vue 组件到 Vue 父级。
- 从 Vue 客户端到服务器。
而且,你可能会对组件数据和道具感到困惑
你可以看看我的回答
//component
Vue.component('price-table', {
props:[
'parentProducts',
],
data: function() {
return {
products:[]
};
},
methods: {
updatePrice(){
console.log('update prices from component to parent');
console.log(this.products);
this.$emit('update-prices', this.products);
}
},
mounted:function(){
console.log('pass products from parent to component');
this.products = this.parentProducts;
}
});
//parent
var vm = new Vue({
el: '#app',
data: () => ({
products:[
{
name:'Apple',
price:'10'
},
{
name:'Banana',
price:'12'
},
{
name:'Coconut',
price:'20'
},
]
}),
methods:{
savePricesToServer(products){
console.log('save prices to server');
console.log(products);
//do ajax here
}
}
});
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h2>Price Table</h2>
<price-table
inline-template
:parent-products="products"
v-on:update-prices="savePricesToServer"
>
<div>
<table border='1' width="100%">
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr v-for="(product, productIndex) in products" :key="productIndex">
<td>{{ product.name}}</td>
<td>
<input type="number" v-model="product.price">
</td>
</tr>
</table>
<button @click="updatePrice">Update Price</button>
</div>
</price-table>
</div>
</body>
</html>
它展示了如何使用自定义事件将数据从组件传递回父级https://vuejs.org/v2/guide/components-custom-events.html
推荐阅读
- wpf - ScrollViewer (VerticalScrollBar) 中的垂直条不与用户控件一起显示,如 WPF XAML 中的扩展器
- qiskit - 没有名为“qiskit_metal”的模块
- java - Jave,报告不显示碧玉报告
- javascript - 使用 async-await 按特定顺序执行 javascript 函数
- javascript - javascript 未加载图像错误::ERR_FILE_NOT_FOUND
- php - 无法使用 onblur 函数发送多个表单变量
- r - 即使设置了语言环境,data.frames 中的藏文字符也无法在 R 控制台中显示(中文很好,矩阵中的藏文很好)
- python - 删除像素图 PyQt
- php - 我正在尝试在我的 Blade.php 文件中显示数据库中的数据,但我收到此错误“尝试获取非对象的属性‘名称’”
- scala - Scala 3 匹配类型和 F 有界类型:“无法证明”