Vue没有更新组件,因为它是在此实例之外定义的?

时间:2017-05-25 21:21:12

标签: javascript vue.js

我正在尝试将Vue用作购物车的实现。

发生的事情的细分:

1)在一个立即调用的匿名函数中,进行api调用以将我的产品的更新列表解析为一个对象并设置到本地存储中。

2)函数,updateCart和addToCart在我看到的教程中的cartStorage对象中:Vue Tutorial

3)创建了Vue实例,将数据绑定到我的购物车

错误:方法“items”未在实例上定义,但在渲染期间引用,没有任何渲染

代码:

IIAF:         var storage = window.localStorage;

    (function() {
        var url = "http://shop.domeha.com/api/v1/products.json";
        $.get(url , function() {
            console.log('Running...')
        })
        .fail(function(err){
            console.log(err)
        })
        .done(function(res) {
            console.log(res)

            var products = res.products.map(function(element) {
                return {
                        name: element.name, 
                        image: element.master.images[0].small_url,
                        id: element.id,
                        price: parseFloat(element.price), 
                        display_price: element.display_price 
                }
            }) // End Map

            products = {
                products: products
            }

            products = JSON.stringify(products);
            storage.setItem('domehaProducts', products)
            console.log('success: ' + products)
        })
        .always(function(res) {
            console.log('Done with: ' + res.body)
        }) }());`

使用Watch的对象和Vue实例:

 var cartStorage = {
        fetch: function() {
            var cart = JSON.parse(localStorage.getItem('domehaCart'))
        },
        addToCart: function (id) {
            q = $('.shopify-buy__quantity').val();
            q = parseInt(q);
            // if key exists
            if (storage.getItem('domehaOrder') != undefined) {
                var order = storage.getItem('domehaOrder')
                order = JSON.parse(order)

                            console.log("idFilter: " + id)
                            //Returns the ID
                            strID = id.toString();


                            filteredOrder = order.items.filter(function(e) {
                                return e.productID == strID;
                            })

                            console.log("filtered" + JSON.stringify(filteredOrder))



                            if (filteredOrder.length == 0) {
                                order.items.push({"productID": id, "quantity": q})
                            } else {
                            // Returns eveything but the ID
                                newArray = order.items.filter(function(e) {
                                    return e.productID != strID;
                                });

                                console.log("newArray" + JSON.stringify(newArray))
                                order = {
                                    items: newArray
                                };
                                console.log("Q: " + JSON.stringify(filteredOrder[0]))
                                q = parseInt(filteredOrder[0].quantity) + q;
                                order.items.push({"productID": id, "quantity":q});
                            }

                                order = JSON.stringify(order)
                                console.log('order: ' + order)
                                storage.setItem('domehaOrder', order)
                                updateCart()



                        } else { 
                            var order = {items: []}
                            order.items.push({"productID": id, "quantity": q})
                            console.log('order: ' + order)
                            order = JSON.stringify(order)
                            storage.setItem('domehaOrder', order)
                            updateCart()
                        } // else 
                },

                updateCart: function() {
                            // if key exists
                        if (storage.getItem('domehaOrder') != undefined) {
                            //jQuery('.quantity').css('display', 'inline-block')
                            //jQuery('.top-cart-item-image').css('display', 'block')

                            //Get local storage order
                            var order = storage.getItem('domehaOrder')

                            //get local storage products


                            // Parse existing order & products// local storage Must be string
                            order = JSON.parse(order);
                            console.log(order)

                            //Get product data from spree backend
                            storeobj = JSON.parse(storage.getItem('domehaProducts'));
                            console.log("Store: " + JSON.stringify(storeobj))




                        // Merge products and cart data
                        var domecart = order.items.map(function(item) {
                        merge = storeobj.products.filter(function(prod) {
                                return prod.id == item.productID;
                            })[0];
                            return Object.assign(item, { images: merge.image, name: merge.name, price: merge.display_price, intPrice: merge.price});
                        });

                        console.log("cart "+ JSON.stringify(domecart))
                        //Grab Total    
                        var total = domecart.map(function(a) {return a.intPrice * a.quantity}).reduce((a, b) => a + b, 0);
                        total = Number(total).toFixed(2);


                        var quantity = domecart.map(function(a) {return a.quantity}).reduce((a, b) => a + b, 0);
                        console.log(quantity)
                        // Refactor for KO

                        domecart = domecart.map(function(e) {
                            return {
                                price: "$" + e.intPrice * e.quantity,
                                images: e.images,
                                name: e.name,
                                quantity: e.quantity,
                                id: e.productID
                            }
                        });

                        console.log("domecart" + domecart)
                        newcart = {
                            items: domecart, 
                            total: "$" + total,
                            quantity: "x " + quantity,
                        }
                        console.log("final cart" + JSON.stringify(newcart))
                        //// Bind to KO

                        //Strinify and save for later
                        domecart = JSON.stringify(newcart)
                        storage.setItem('domehaCart', domecart)

                        } else {
                            // Cart is empty
                            jQuery('#cart').html("<h1 style='text-align:center; padding:2rem;'>The cart is empty</h1>")
                        }
                    }
                } 
        cartStorage.updateCart();
        var vue = new Vue({
            el: '#cart',
            data: {
                cart: cartStorage.fetch()
               },
            watch: {
                cart: {
                    handler: function(cart) {
                        cartStorage.updateCart()
                    },
                    deep: true
                }
            }
        });`

现在,如果您不想全部使用这些功能,那么更新购物车,ajaxcall和addToCart都可以正常工作....

单击按钮时所需的行为 <button onclick="cartStoreage.addToCart(id)</button>

购物车将自动使用新数量进行更新。

购物车对象如下所示:{"items":[{"price":"$499.97","images":"https://s3.us-east-2.amazonaws.com/dome-web-assets/spree/images/attachments/000/000/002/small/zwave-group.png?1495122722","name":"Dealer Bundle","quantity":1,"id":1},{"price":"$13341.99","images":"https://s3.us-east-2.amazonaws.com/dome-web-assets/spree/images/attachments/000/000/003/small/siren.jpg?1495298098","name":"Siren Sensor","quantity":267,"id":2}],"total":"$13841.96","quantity":"x 268"}

Vues devtools插件将cart定义为undefined,并且在vue抛出该错误之前fetch()函数也会被调用rught ...

我该如何解决这个问题?

0 个答案:

没有答案