【问题标题】:how to alterate state in array object at v-for loop?如何在 v-for 循环中更改数组对象中的状态?
【发布时间】:2021-05-29 18:52:36
【问题描述】:

我正在使用 Nuxt 在 Vue Js 制作库存系统。我试图创建一个在库存中找到的功能,如果该项目存在于库存中,则数量增加一个。问题?该函数成功运行,但我看不到我的 V-for 列表中的变化,但如果我在我的数组中推送其他对象,则 v-for 循环将使用新数据进行更新。

<script lang="js">
    import Vue from 'vue'
    import Navbar from '../../components/Navbar'
    export default Vue.extend({
        components: {
            Navbar
        },
        data(){
            return{
                products: [
                    { name: 'abrazadera', id: 0, image: "https://carritoferretero.com/wp-content/uploads/2018/05/products-abrazadera-de-arranque-carrito-ferretero_2.png", price: 20},
                    { name: 'tuerca', id: 1, image: "https://cdn.homedepot.com.mx/productos/819576/819576-d.jpg", price: 40},
                    { name: 'martillo', id: 2, image: "https://cdn.homedepot.com.mx/productos/680442/680442-d.jpg", price: 50}
                ],
                venta: [

                ]
            }
        },
        methods: {
            addProduct(id, index){
                let busqueda = this.venta.find( item => item.id == id)
                console.log(busqueda)
                if(typeof(busqueda) == 'undefined'){
                    let newObj = this.products[index]
                    newObj.cantidad = 1
                    this.venta.push(newObj)
                } else {
                    busqueda = this.venta.findIndex( element  => element.id == id )
                    let newObj = this.venta[busqueda]
                    newObj.cantidad = this.venta[busqueda].cantidad + 1
                    this.venta[busqueda] = newObj
                }
            }
        }
    })
</script>

在我的“addProduct”函数中,如果项目不存在,我会在我的“venta”库存中找到一个产品,我在我的库存中添加一个产品,否则我添加 + 1 个数量。该功能正常工作,但渲染 vfor 没有更新。仅当我使用“arrayelement.push”添加新元素时,v-for 列表才会更新

有什么办法解决这个问题吗?感谢您的回答

【问题讨论】:

    标签: javascript vue.js linux-toolchain


    【解决方案1】:

    Vue 2 无法检测到以常规方式对数组中现有项目的更改; here's the full explanation。您需要更改此行:

    this.venta[busqueda] = newObj
    

    到:

    this.venta.splice(busqueda, 1, newObj)
    

    (你也可以使用Vue.set,但splice至少仍然是标准的数组操作。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 2023-04-10
      • 2022-10-13
      • 2020-02-14
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      相关资源
      最近更新 更多