首页 > 解决方案 > 不知道如何在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>

标签: laravelvue.jslaravel-8

解决方案


您的问题是关于数据传递的两个部分。

  1. 从 Vue 组件到 Vue 父级。
  2. 从 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


推荐阅读