【发布时间】:2018-08-21 15:56:13
【问题描述】:
我有一个基于 Vue (1.x) 的购物篮系统,它与使用 Moltin-Cart 的 Laravel 后端一起工作。使用对后端的 API 调用填充、检索和更新购物篮。
我可以毫无问题地将物品添加到购物篮中:
addToBasket: function(){
var that = this;
var item = this.book;
this.$http.post('/api/buy/addToBasket', item);
this.basketAddSuccess = true;
setTimeout(function(){ that.basketAddSuccess = false; }, 4000);
}
命中后端:
public function addToBasket(Request $request)
{
// grab book information
$book = Book::find($request->id);
// extract price from the database to ensure it's correct
$row = $book->price;
// create an item
$item = array(
'id' => $book->id,
'name' => $book->title,
'price' => $row,
'quantity' => $request->qty
);
// Make the insertion...
$this->cart->insert($item);
}
当我点击我的 fetchBasket API 函数时,我得到了预期的结果:
{
027c91341fd5cf4d2579b49c4b6a90da: {
id: 1,
name: "Book Title",
price: 40,
quantity: "1"
}
}
长的随机字符串是购物车ID。
当我尝试使用简单的 v-for 列出购物篮内容时出现问题:
<tr v-for="item in basketItems">
但这会引发很多错误:
[Vue warn]: Duplicate value found in v-for="item in basketItems": "0". Use track-by="$index" if you are expecting duplicate values.
事实上,JSON 字符串中的每个字符都有一个错误。
所以谷歌搜索我找到track-by 并尝试先用 item.id 实现它:
<tr v-for="item in basketItems" track-by="item.id">
这会抛出
VM4389:3 Uncaught TypeError: Cannot read property 'id' of undefined
然后用 $index:
<tr v-for="item in basketItems" track-by="$index">
这不会引发错误,而是会在购物篮视图中为 JSON 字符串中的每个字符创建一个空的购物篮项目条目。
关于如何解决它的任何想法?
编辑:
public function fetchBasket()
{
return ($this->cart->contents(true));
}
【问题讨论】:
-
你能显示 fetchBasket API 代码吗?
-
你的响应是一个对象,你把它当作一个数组来对待
-
@VaibhavrajRoham 添加。 'true' 标志将内容设置为作为数组返回(由于某种原因实际上是一个对象)。
标签: javascript php laravel vue.js